forked from Daij-Djan/proximity
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathProximityBluetoothMonitor.m
110 lines (91 loc) · 2.56 KB
/
ProximityBluetoothMonitor.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
//
// ProximityBluetoothMonitor.m
// Proximity
//
// Created by Dominik Pich on 8/1/12.
//
//
#import "ProximityBluetoothMonitor.h"
@implementation ProximityBluetoothMonitor {
NSTimer *_timer;
}
- (id)init {
self = [super init];
if(self) {
_priorStatus = _status = ProximityBluetoothStatusUndefined;
_timeInterval = kDefaultPageTimeout;
_requiredSignalStrength = NO;
}
return self;
}
- (void)start {
[_timer invalidate];
_timer = [NSTimer scheduledTimerWithTimeInterval:_timeInterval
target:self
selector:@selector(handleTimer:)
userInfo:nil
repeats:YES];
}
- (void)stop {
[_timer invalidate];
_timer = nil;
_priorStatus = _status;
_status = ProximityBluetoothStatusUndefined;
}
- (void)refresh {
[self handleTimer:_timer];
}
- (void)setTimeInterval:(NSTimeInterval)timeInterval {
if(_timeInterval < kDefaultPageTimeout)
_timeInterval = kDefaultPageTimeout;
_timeInterval = timeInterval;
if(_timer) {
[self start];
}
}
#pragma mark
- (void)handleTimer:(NSTimer *)theTimer
{
BOOL inRange = [self isInRange];
#ifdef DEBUG
NSLog(@"BT device %@ inRange:%d",_device.name, inRange);
#endif
_status = inRange ? ProximityBluetoothStatusInRange : ProximityBluetoothStatusOutOfRange;
if( inRange ) {
if( _priorStatus != ProximityBluetoothStatusInRange ) {
_priorStatus = ProximityBluetoothStatusInRange;
[_delegate proximityBluetoothMonitor:self foundDevice:_device];
#ifdef DEBUG
NSLog(@"-- found");
#endif
}
}
else {
if( _priorStatus != ProximityBluetoothStatusOutOfRange ) {
_priorStatus = ProximityBluetoothStatusOutOfRange;
[_delegate proximityBluetoothMonitor:self lostDevice:_device];
#ifdef DEBUG
NSLog(@"-- lost");
#endif
}
}
}
- (BOOL)isInRange
{
if(!_device)
return NO;
IOReturn br = [_device openConnection:nil withPageTimeout:kDefaultPageTimeout authenticationRequired:NO];
if(br == kIOReturnSuccess) {
// BluetoothHCIRSSIValue rawRssi = [_device rawRSSI];
BluetoothHCIRSSIValue rssi = [_device RSSI];
#ifdef DEBUG
// if(rssi!=0)
NSLog(@"RSSI of %@: %d/%d", _device.name, rssi, _requiredSignalStrength);
#endif
BOOL inRange = rssi>=_requiredSignalStrength;
[_device closeConnection];
return inRange;
}
return NO;
}
@end