Skip to content

Instantly share code, notes, and snippets.

@liamnichols
Last active July 8, 2022 22:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liamnichols/7505120 to your computer and use it in GitHub Desktop.
Save liamnichols/7505120 to your computer and use it in GitHub Desktop.
Detects iBeacons in the area and parses their data (mac app using CBCentralManager)
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
self.manager = [[CBCentralManager alloc] initWithDelegate:self queue:nil options:nil];
}
-(void)centralManagerDidUpdateState:(CBCentralManager *)central
{
if (self.manager.state == CBCentralManagerStatePoweredOn)
{
[self.manager scanForPeripheralsWithServices:nil options:nil];
}
}
-(void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
NSData *advData = [advertisementData objectForKey:@"kCBAdvDataManufacturerData"];
if ([self advDataIsBeacon:advData])
{
NSDictionary *beacon = [self getBeaconInfoFromData:advData];
NSLog(@"found beacon: %@ with RSSI: %@",beacon, RSSI);
}
}
- (BOOL)advDataIsBeacon:(NSData *)data
{
//TODO: could this be cleaner?
Byte expectingBytes [4] = { 0x4c, 0x00, 0x02, 0x15 };
NSData *expectingData = [NSData dataWithBytes:expectingBytes length:sizeof(expectingBytes)];
if (data.length > expectingData.length)
{
if ([[data subdataWithRange:NSMakeRange(0, expectingData.length)] isEqual:expectingData])
{
return YES;
}
}
return NO;
}
- (NSDictionary *)getBeaconInfoFromData:(NSData *)data
{
NSRange uuidRange = NSMakeRange(4, 16);
NSRange majorRange = NSMakeRange(20, 2);
NSRange minorRange = NSMakeRange(22, 2);
NSRange powerRange = NSMakeRange(24, 1);
Byte uuidBytes[16];
[data getBytes:&uuidBytes range:uuidRange];
NSUUID *uuid = [[NSUUID alloc] initWithUUIDBytes:uuidBytes];
int16_t majorBytes;
[data getBytes:&majorBytes range:majorRange];
int16_t majorBytesBig = (majorBytes >> 8) | (majorBytes << 8);
int16_t minorBytes;
[data getBytes:&minorBytes range:minorRange];
int16_t minorBytesBig = (minorBytes >> 8) | (minorBytes << 8);
int8_t powerByte;
[data getBytes:&powerByte range:powerRange];
return @{ @"uuid" : uuid, @"major" : @(majorBytesBig), @"minor" : @(minorBytesBig), @"power" : @(powerByte) };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment