Class: Tgios::BeaconManager

Inherits:
BindingBase show all
Defined in:
lib/tgios/beacon_manager.rb

Constant Summary collapse

ALGORITHMS =
[:continue, :timeout]
BeaconFoundKey =
'Tgios::BeaconManager::BeaconFound'
BeaconsFoundKey =
'Tgios::BeaconManager::BeaconsFound'
RangingFailedKey =
'Tgios::BeaconManager::RangingFailed'
EnterRegionKey =
'Tgios::BeaconManager::EnterRegion'
ExitRegionKey =
'Tgios::BeaconManager::ExitRegion'
BluetoothChangedKey =
'Tgios::BeaconManager::BluetoothChanged'

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BindingBase

#hook, #prepareForRelease, #unhook

Constructor Details

#initialize(options) ⇒ BeaconManager

range_method: :rssi or :accuracy range_limit: around -70 for :rssi / around 1.5 (meters) for :accuracy background: range beacons when device is in background algorithm: :continue or :timeout tolerance: for algorithm continue: number of times a beacon is ranged continuously required to trigger beacon changed event, for algorithm timeout: time in seconds for a beacon marked as changed



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
# File 'lib/tgios/beacon_manager.rb', line 52

def initialize(options)
  @events = {}
  @previous_beacons = []
  @beacons_last_seen_at = {}
  @background = options[:background]

  self.algorithm = (options[:algorithm] || :continue)
  @tolerance = (options[:tolerance] || 5)

  @range_method = (options[:range_method] || :rssi)
  @range_limit = (options[:range_limit] || -70)

  @regions = []
  region_options = options[:regions]
  if !region_options.is_a?(Array)
    region_options = [{uuid: options[:uuid], major: options[:major], minor: options[:minor]}]
  end

  region_options.each do |region_hash|
    if region_hash.is_a?(Hash)
      uuid = region_hash[:uuid]
      major = region_hash[:major]
      minor = region_hash[:minor]
    else
      uuid = region_hash
    end
    uuid = uuid.upcase
    nsuuid = NSUUID.alloc.initWithUUIDString(uuid)
    region = if major && minor
               CLBeaconRegion.alloc.initWithProximityUUID(nsuuid, major: major, minor: minor, identifier: identifier(uuid, major, minor))
             elsif major
               CLBeaconRegion.alloc.initWithProximityUUID(nsuuid, major: major, identifier: identifier(uuid, major, minor))
             else
               CLBeaconRegion.alloc.initWithProximityUUID(nsuuid, identifier: identifier(uuid, major, minor))
             end
    @regions << {region: region, active: false}

    region.notifyOnEntry = true
    region.notifyOnExit = true
    region.notifyEntryStateOnDisplay = true
  end

  central_manager
  start_monitor

  UIApplicationWillEnterForegroundNotification.add_observer(self, 'on_enter_foreground:')
  UIApplicationDidEnterBackgroundNotification.add_observer(self, 'on_enter_background:')

end

Instance Attribute Details

#backgroundObject

Returns the value of attribute background.



25
26
27
# File 'lib/tgios/beacon_manager.rb', line 25

def background
  @background
end

#current_beaconObject

Returns the value of attribute current_beacon.



25
26
27
# File 'lib/tgios/beacon_manager.rb', line 25

def current_beacon
  @current_beacon
end

#current_bluetooth_stateObject (readonly)

Returns the value of attribute current_bluetooth_state.



26
27
28
# File 'lib/tgios/beacon_manager.rb', line 26

def current_bluetooth_state
  @current_bluetooth_state
end

#range_limitObject

Returns the value of attribute range_limit.



25
26
27
# File 'lib/tgios/beacon_manager.rb', line 25

def range_limit
  @range_limit
end

#range_methodObject

Returns the value of attribute range_method.



25
26
27
# File 'lib/tgios/beacon_manager.rb', line 25

def range_method
  @range_method
end

#toleranceObject

Returns the value of attribute tolerance.



25
26
27
# File 'lib/tgios/beacon_manager.rb', line 25

def tolerance
  @tolerance
end

Class Method Details

.beacon_eqs(beacon1, beacon2) ⇒ Object



346
347
348
349
# File 'lib/tgios/beacon_manager.rb', line 346

def self.beacon_eqs(beacon1, beacon2)
  return beacon1 == beacon2 if beacon1.nil? || beacon2.nil?
  beacon1.minor == beacon2.minor && beacon1.major == beacon2.major && beacon1.proximityUUID.UUIDString.upcase == beacon2.proximityUUID.UUIDString.upcase
end

.beacon_in_region(beacon, region) ⇒ Object



356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
# File 'lib/tgios/beacon_manager.rb', line 356

def self.beacon_in_region(beacon, region)
  return false unless beacon

  match = beacon.proximityUUID == region.proximityUUID
  return false unless match
  major = region.major
  if major
    match = match && beacon.major == major
    return false unless match
    minor = region.minor
    if minor
      match = match && beacon.minor == minor
    end
  end
  match
end

.beacon_key(beacon) ⇒ Object



373
374
375
# File 'lib/tgios/beacon_manager.rb', line 373

def self.beacon_key(beacon)
  [beacon.try(:proximityUUID).try(:UUIDString).try(:upcase), beacon.try(:major), beacon.try(:minor)].join('/')
end

.defaultObject



40
41
42
# File 'lib/tgios/beacon_manager.rb', line 40

def self.default
  @default
end

.default=(val) ⇒ Object



36
37
38
# File 'lib/tgios/beacon_manager.rb', line 36

def self.default=(val)
  @default = val
end

.region_eqs(region1, region2) ⇒ Object



351
352
353
354
# File 'lib/tgios/beacon_manager.rb', line 351

def self.region_eqs(region1, region2)
  return region1 == region2 if region1.nil? || region2.nil?
  region1.identifier.upcase == region2.identifier.upcase
end

.supportedObject



390
391
392
# File 'lib/tgios/beacon_manager.rb', line 390

def self.supported
  CLLocationManager.isRangingAvailable
end

Instance Method Details

#algorithm=(val) ⇒ Object

Raises:

  • (ArgumentError)


111
112
113
114
115
116
117
118
119
120
# File 'lib/tgios/beacon_manager.rb', line 111

def algorithm=(val)
  alg = val.to_s.to_sym
  return unless alg.present?
  if @algorithm != alg
    @previous_beacons.clear
  end
  raise ArgumentError.new("Algorithm not found, valid algorithm are: [#{ALGORITHMS.join(', ')}]") unless ALGORITHMS.include?(alg)

  @algorithm = alg
end

#beacon_eqs(beacon1, beacon2) ⇒ Object



342
343
344
# File 'lib/tgios/beacon_manager.rb', line 342

def beacon_eqs(beacon1, beacon2)
  self.class.beacon_eqs(beacon1, beacon2)
end

#central_managerObject



270
271
272
# File 'lib/tgios/beacon_manager.rb', line 270

def central_manager
  @central_manager ||= CBCentralManager.alloc.initWithDelegate(self, queue: nil)
end

#centralManagerDidUpdateState(central) ⇒ Object



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
# File 'lib/tgios/beacon_manager.rb', line 274

def centralManagerDidUpdateState(central)
  state = central.state
  @current_bluetooth_state = state

  if has_event(:bluetooth_changed)
    @events[:bluetooth_changed].call(state)
  end
  BluetoothChangedKey.post_notification(self, {state: state})

  @regions.each do |region_hash|
    region = region_hash[:region]
    case state
      when CBCentralManagerStatePoweredOff, CBCentralManagerStateUnsupported, CBCentralManagerStateUnauthorized
        did_exit_region(region)
      when CBCentralManagerStatePoweredOn
        did_enter_region(region)
      when CBCentralManagerStateResetting
      when CBCentralManagerStateUnknown
      else
    end
  end
end

#deallocObject



405
406
407
408
# File 'lib/tgios/beacon_manager.rb', line 405

def dealloc
  onPrepareForRelease
  super
end

#did_enter_region(region) ⇒ Object



233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/tgios/beacon_manager.rb', line 233

def did_enter_region(region)
  if region.isKindOfClass(CLBeaconRegion)

    region_hash = get_region_hash(region)
    return if region_hash.blank?
    region_hash[:active] = true

    location_manager.startRangingBeaconsInRegion(region)
    if has_event(:enter_region)
      @events[:enter_region].call(region)
    end
    EnterRegionKey.post_notification(self, {region: region})
  end
end

#did_exit_region(region) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
# File 'lib/tgios/beacon_manager.rb', line 248

def did_exit_region(region)
  if region.isKindOfClass(CLBeaconRegion)

    region_hash = get_region_hash(region)
    return if region_hash.blank?
    region_hash[:active] = false

    location_manager.stopRangingBeaconsInRegion(region)
    @previous_beacons.delete_if {|b|
      beacon = b.is_a?(Hash) ? b[:beacon] : b
      self.class.beacon_in_region(beacon, region)
    }
    if self.class.beacon_in_region(@current_beacon, region)
      @current_beacon = nil
    end
    if has_event(:exit_region)
      @events[:exit_region].call(region)
    end
    ExitRegionKey.post_notification(self, {region: region})
  end
end

#get_region_hash(region) ⇒ Object



384
385
386
387
# File 'lib/tgios/beacon_manager.rb', line 384

def get_region_hash(region)
  region_hash = @regions.find{|r| self.class.region_eqs(r[:region], region) }
  region_hash || {}
end

#has_event(event) ⇒ Object



297
298
299
# File 'lib/tgios/beacon_manager.rb', line 297

def has_event(event)
  @events.has_key?(event)
end

#identifier(uuid, major, minor) ⇒ Object



102
103
104
# File 'lib/tgios/beacon_manager.rb', line 102

def identifier(uuid, major, minor)
  [uuid, major, minor].join('/')
end

#location_managerObject



177
178
179
180
181
182
183
184
185
# File 'lib/tgios/beacon_manager.rb', line 177

def location_manager
  @location_manager ||=
      begin
        manager = CLLocationManager.alloc.init
        manager.delegate = self
        request_authorization(manager)
        manager
      end
end

#locationManager(manager, rangingBeaconsDidFailForRegion: region, withError: error) ⇒ Object



122
123
124
125
126
127
128
129
130
# File 'lib/tgios/beacon_manager.rb', line 122

def locationManager(manager, didDetermineState: state, forRegion: region)
  NSLog "didDetermineState #{state}"
  if state == CLRegionStateInside
    manager.startRangingBeaconsInRegion(region)
    did_enter_region(region)
  elsif state == CLRegionStateOutside
    did_exit_region(region)
  end
end

#new_fake_beacon(options) ⇒ Object



377
378
379
380
381
382
# File 'lib/tgios/beacon_manager.rb', line 377

def new_fake_beacon(options)
  region_hash = @regions.first
  region = region_hash[:region] if region_hash
  region_options = region ? {uuid: region.proximityUUID, major: region.major, minor: region.minor} : {}
  FakeBeacon.new(region_options.merge(options))
end

#on(event_key, &block) ⇒ Object



106
107
108
109
# File 'lib/tgios/beacon_manager.rb', line 106

def on(event_key,&block)
  @events[event_key] = block.weak!
  self
end

#on_enter_background(noti) ⇒ Object



229
230
231
# File 'lib/tgios/beacon_manager.rb', line 229

def on_enter_background(noti)
  stop_monitor unless @background
end

#on_enter_foreground(noti) ⇒ Object



225
226
227
# File 'lib/tgios/beacon_manager.rb', line 225

def on_enter_foreground(noti)
  self.performSelector('start_monitor', withObject: nil, afterDelay:1)
end

#onPrepareForReleaseObject



394
395
396
397
398
399
400
401
402
403
# File 'lib/tgios/beacon_manager.rb', line 394

def onPrepareForRelease
  UIApplicationWillEnterForegroundNotification.remove_observer(self)
  UIApplicationDidEnterBackgroundNotification.remove_observer(self)
  stop_monitor
  @location_manager = nil
  @events = nil
  @current_beacon = nil
  @previous_beacons = nil
  @regions = []
end

#push_beacon(beacon) ⇒ Object



301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/tgios/beacon_manager.rb', line 301

def push_beacon(beacon)
  case @algorithm
    when :continue
      if beacon_eqs(beacon, @current_beacon)
        @current_beacon = beacon
      else
        if @previous_beacons.find { |b| !beacon_eqs(beacon, b) }.blank? # all previous beacons is the new beacon
          @current_beacon = beacon
        else
          @current_beacon = nil if @previous_beacons.find{ |b| beacon_eqs(@current_beacon, b)}.blank? # all previous beacons is not the current beacon
        end
      end
      @previous_beacons << beacon
      @previous_beacons.delete_at(0) if @previous_beacons.length > @tolerance

    when :timeout
      time_now = Time.now
      beacon_hash = {beacon: beacon, time: time_now}
      @beacons_last_seen_at[self.class.beacon_key(beacon)] = beacon_hash

      while @previous_beacons.present? && time_now - @previous_beacons.first[:time] > @tolerance do
        @previous_beacons.delete_at(0)
      end
      @previous_beacons << beacon_hash

      current_beacon_hash = @beacons_last_seen_at[self.class.beacon_key(@current_beacon)]
      if current_beacon_hash

      end
      if !current_beacon_hash || time_now - current_beacon_hash[:time] < @tolerance
         # current beacon not change
      else
        count_hash = @previous_beacons.each_with_object(Hash.new(0)) {|e, h| h[self.class.beacon_key(e[:beacon])] += @tolerance - (time_now - e[:time])} # beacon has more weighting if time is later
        max_beacon_key = count_hash.max_by(&:last).first
        @current_beacon = @beacons_last_seen_at[max_beacon_key][:beacon]
      end
    else
      @current_beacon = beacon
  end
end

#request_authorization(manager) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/tgios/beacon_manager.rb', line 187

def request_authorization(manager)
  if manager.respond_to?(:requestAlwaysAuthorization)
    status = CLLocationManager.authorizationStatus
    if status == KCLAuthorizationStatusAuthorizedWhenInUse || status == KCLAuthorizationStatusDenied
      denied_title = 'Tgios::BeaconManager.request_alert.title.denied'._
      denied_title = 'Location services are off' if denied_title == 'Tgios::BeaconManager.request_alert.title.denied'

      disabled_title = 'Tgios::BeaconManager.request_alert.title.disabled'._
      disabled_title = 'Background location is not enabled' if disabled_title == 'Tgios::BeaconManager.request_alert.title.disabled'

      message = 'Tgios::BeaconManager.request_alert.message'._
      message = "To use background location you must turn on 'Always' in the Location Services Settings" if message == 'Tgios::BeaconManager.request_alert.message'

      title = (status == KCLAuthorizationStatusDenied) ? denied_title : disabled_title
      UIAlertView.alert(title, message: message)
    else
      manager.requestAlwaysAuthorization
    end
  end

end

#start_monitorObject



209
210
211
212
213
214
215
# File 'lib/tgios/beacon_manager.rb', line 209

def start_monitor
  @regions.each do |region_hash|
    region = region_hash[:region]
    location_manager.startMonitoringForRegion(region)
    location_manager.requestStateForRegion(region)
  end
end

#stop_monitorObject



217
218
219
220
221
222
223
# File 'lib/tgios/beacon_manager.rb', line 217

def stop_monitor
  @regions.each do |region_hash|
    region = region_hash[:region]
    location_manager.stopRangingBeaconsInRegion(region)
    location_manager.stopMonitoringForRegion(region)
  end
end