利用CoreLocation.framework很容易扫描得到周边蓝牙设备,苹果开源代码AirLocate有具体实现,下载地址:php
https://developer.apple.com/library/ios/samplecode/AirLocate/Introduction/Intro.html
html
所得到的iBeacon在CoreLocation里以CLBeacon表示,其中有RSSI值(接收信号强度),能够用来计算发射端和接收端间距离。ios
计算公式:app
d = 10^((abs(RSSI) - A) / (10 * n))ide
其中:ui
d - 计算所得距离url
RSSI - 接收信号强度(负值)spa
A - 发射端和接收端相隔1米时的信号强度code
n - 环境衰减因子orm
计算公式的代码实现
- (float)calcDistByRSSI:(int)rssi { int iRssi = abs(rssi); float power = (iRssi-59)/(10*2.0); return pow(10, power); }
因为所处环境不一样,每台发射源(蓝牙设备)对应参数值都不同。按道理,公式里的每项参数都应该作实验(校准)得到。
当你不知道周围蓝牙设备准确位置时,只能给A和n赋经验值(如本例)。
修改AirLocate的APLRangingViewController.m展示部分代码,输出计算距离
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *identifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier]; // Display the UUID, major, minor and accuracy for each beacon. NSNumber *sectionKey = [self.beacons allKeys][indexPath.section]; CLBeacon *beacon = self.beacons[sectionKey][indexPath.row]; cell.textLabel.text = [beacon.proximityUUID UUIDString]; // NSLog(@"%@", [beacon.proximityUUID UUIDString]); // NSString *formatString = NSLocalizedString(@"Major: %@, Minor: %@, Acc: %.2fm, Rssi: %d, Dis: %.2f", @"Format string for ranging table cells."); // cell.detailTextLabel.text = [NSString stringWithFormat:formatString, beacon.major, beacon.minor, beacon.accuracy, beacon.rssi, [self calcDistByRSSI:beacon.rssi]]; NSString *formatString = NSLocalizedString(@"Acc: %.2fm, Rssi: %d, Dis: %.2fm", @"Format string for ranging table cells."); cell.detailTextLabel.text = [NSString stringWithFormat:formatString, beacon.accuracy, beacon.rssi, [self calcDistByRSSI:beacon.rssi]]; return cell; }
展示了每台蓝牙设备的Acc(精度)、Rssi(信号强度)和Dis(距离)。