Отредактировано: удален код iBeacon. Так как нет проблем с кодом iBeacon.
-> Как только мы распознаем наши маяки, мы должны связаться с первым маяком, используя BLE. Мы используем фреймворк Bleno на Respberry PI.
//Передача моего сервисного UUID
[bluetoothManager scanForPeripheralsWithServices:@[@"87fa7df2-748c-4093-8e73-b93ee73543b4"] options:scanOptions];
Проблема в том, что если мы передаем UUID моей службы (проверено с помощью приложения Light Blue), я не получаю никаких результатов. Вместо этого, если мы передаем «ноль», я, по крайней мере, могу распознать свое устройство.
Итак, есть ли какой-либо общий способ распознать наше устройство Bluetooth из кода iOS. Поскольку CBPeripheral возвращает ограниченные свойства.
‹CBPeripheral: 0x1700ff700, идентификатор = 7915DCF8-AF2E-4AF2-B5FC-A5EEA10D3812, имя = raspberrypi, состояние = подключено›
Я попытался изменить имя своего устройства Bluetooth, используя приведенную ниже команду, используя структуру BLENO.
sudo BLENO_DEVICE_NAME="SOME_NAME_86" узел iBeacon.js
Иногда я могу прочитать имя. Но не всегда. Поэтому ищу альтернативное решение.
Вот мой код:
@реализация ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
_data = [[NSMutableData alloc] init];
}
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
switch (central.state) {
case CBManagerStatePoweredOn:
[_centralManager scanForPeripheralsWithServices:@[[CBUUID
UUIDWithString:@"87FA7DF2-748C-4093-8E73-B93EE73543B4"]] options:@{CBCentralManagerScanOptionAllowDuplicatesKey : @YES}]; break;
default: break;
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI {
if (_discoveredPeripheral != peripheral) {
_discoveredPeripheral = peripheral;
[_centralManager connectPeripheral:peripheral options:nil];
[_centralManager stopScan];
}
}
- (void)centralManager:(CBCentralManager *)central didFailToConnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error {
NSLog(@"Failed to connect");
[self cleanup];
}
- (void)cleanup {
// See if we are subscribed to a characteristic on the peripheral
if (_discoveredPeripheral.services != nil) {
for (CBService *service in _discoveredPeripheral.services) {
if (service.characteristics != nil) {
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID isEqual:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]]) {
if (characteristic.isNotifying) {
[_discoveredPeripheral setNotifyValue:NO forCharacteristic:characteristic];
return;
}
}
}
}
}
}
[_centralManager cancelPeripheralConnection:_discoveredPeripheral];
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
NSLog(@"Connected");
[_centralManager stopScan];
NSLog(@"Scanning stopped");
[_data setLength:0];
peripheral.delegate = self;
[peripheral discoverServices:@[[CBUUID UUIDWithString:@"87FA7DF2-748C-4093-8E73-B93EE73543B4"]]];
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
[self cleanup];
return;
}
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:@[[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]] forService:service];
}
// Discover other characteristics
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
NSLog(@"Error");
return;
}
NSString *stringFromData = [[NSString alloc] initWithData:characteristic.value encoding:NSUTF8StringEncoding];
if ([stringFromData isEqualToString:@"EOM"]) {
[peripheral setNotifyValue:NO forCharacteristic:characteristic];
[_centralManager cancelPeripheralConnection:peripheral];
}
[_data appendData:characteristic.value];
}
@конец
Проблема в том, что у меня есть два устройства Bluetooth рядом, рекламирующие один и тот же идентификатор службы. Исходя из сценария, я должен подключиться только к одному устройству и прочитать его характеристики.