Class: ScanBeacon::BeaconParser

Inherits:
Object
  • Object
show all
Defined in:
lib/scan_beacon/beacon_parser.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(beacon_type, layout) ⇒ BeaconParser

Returns a new instance of BeaconParser.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/scan_beacon/beacon_parser.rb', line 6

def initialize(beacon_type, layout)
  @beacon_type = beacon_type
  @layout = layout.split(",")
  @matchers = @layout.find_all {|item| item[0] == "m"}.map {|matcher|
    _, range_start, range_end, expected = matcher.split(/:|=|-/)
    {start: range_start.to_i, end: range_end.to_i, expected: expected}
  }
  @ids = @layout.find_all {|item| item[0] == "i"}.map {|id|
    _, range_start, range_end = id.split(/:|-/)
    {start: range_start.to_i, end: range_end.to_i}
  }
  _, power_start, power_end = @layout.find {|item| item[0] == "p"}.split(/:|-/)
  @power = {start: power_start.to_i, end: power_end.to_i}
end

Instance Attribute Details

#beacon_typeObject

Returns the value of attribute beacon_type.



4
5
6
# File 'lib/scan_beacon/beacon_parser.rb', line 4

def beacon_type
  @beacon_type
end

Instance Method Details

#inspectObject



49
50
51
# File 'lib/scan_beacon/beacon_parser.rb', line 49

def inspect
  "<BeaconParser type=\"#{@beacon_type}\", layout=\"#{@layout.join(",")}\">"
end

#matches?(data) ⇒ Boolean

Returns:

  • (Boolean)


21
22
23
24
25
26
# File 'lib/scan_beacon/beacon_parser.rb', line 21

def matches?(data)
  @matchers.each do |matcher|
    return false unless data[matcher[:start]..matcher[:end]].unpack("H*").join == matcher[:expected]
  end
  return true
end

#parse(data) ⇒ Object



28
29
30
31
# File 'lib/scan_beacon/beacon_parser.rb', line 28

def parse(data)
  return nil if !matches?(data)
  Beacon.new(ids: parse_ids(data), power: parse_power(data), beacon_type: @beacon_type)
end

#parse_ids(data) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/scan_beacon/beacon_parser.rb', line 33

def parse_ids(data)
  @ids.map {|id|
    if id[:end] - id[:start] == 1
      # two bytes, so treat it as a short (big endian)
      data[id[:start]..id[:end]].unpack('S>')[0]
    else
      # not two bytes, so treat it as a hex string
      data[id[:start]..id[:end]].unpack('H*').join
    end
  }
end

#parse_power(data) ⇒ Object



45
46
47
# File 'lib/scan_beacon/beacon_parser.rb', line 45

def parse_power(data)
  data[@power[:start]..@power[:end]].unpack('c')[0]
end