Class: TagIt::TagTracker

Inherits:
Object
  • Object
show all
Includes:
Observable, Timeout
Defined in:
lib/tag_it/tag_tracker.rb

Instance Method Summary collapse

Constructor Details

#initialize(port) ⇒ TagTracker

Returns a new instance of TagTracker.



9
10
11
12
13
# File 'lib/tag_it/tag_tracker.rb', line 9

def initialize(port)
  @port = port
  @tag_map ||= {}
  @last_pulse = Time.now
end

Instance Method Details

#depart_all_tags!Object



57
58
59
60
61
62
63
# File 'lib/tag_it/tag_tracker.rb', line 57

def depart_all_tags!
  @tag_map.keys.each do |tag_name|
    changed
    notify_observers(tag_name,0,:tag_departed)
  end
  @tag_map.clear
end

#depart_dormant_tags!Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/tag_it/tag_tracker.rb', line 65

def depart_dormant_tags!
  tags_to_depart = []
  @tag_map.each do |tag_name,last_time|
    tags_to_depart << tag_name if((Time.now - last_time) > 8)
  end
  
  tags_to_depart.each do |tag_name|
    changed
    notify_observers(tag_name,0,:tag_departed)
    @tag_map.delete(tag_name)
  end
end

#flush_tag!(tag_name) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/tag_it/tag_tracker.rb', line 48

def flush_tag!(tag_name)
  tag_name,strength = split_tag_data(tag_name)
  if @tag_map[tag_name].nil?
    changed
    notify_observers(tag_name,strength,:tag_arrived)
  end
  @tag_map[tag_name] = Time.now
end

#pulse!Object



82
83
84
85
86
# File 'lib/tag_it/tag_tracker.rb', line 82

def pulse!
  changed
  notify_observers(@tag_map.keys.sort,0,:pulse)
  @last_pulse = Time.now
end

#split_tag_data(tag_name) ⇒ Object



78
79
80
# File 'lib/tag_it/tag_tracker.rb', line 78

def split_tag_data(tag_name)
  [tag_name[0,4],tag_name[4,tag_name.size - 4].to_i]
end

#start!Object



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
# File 'lib/tag_it/tag_tracker.rb', line 15

def start!
  char = nil
  tag_name = ""
  
  #dont start reporting until after the first space, 
  #so we don't have to deal with partial tagnames
  clean_start_flag = false 
  
  #128 is the stop character we're adding so the tests can cutoff the loop.  
  #Production will loop infinitely until shutdown
  while char != 128  
    begin
      # Don't take longer than 3 seconds to find a char, or there aren't any
      Timeout::timeout(3) do
        char = @port.getc
      end
      if char == 32 
        flush_tag!(tag_name) if clean_start_flag #don't send until after first space
        depart_dormant_tags!
        tag_name = ""
        clean_start_flag = true #here's a space, start sending tags
      else
        tag_name = "#{tag_name}#{char.chr}"
      end
    rescue Timeout::Error
      depart_all_tags!
    end
    if ((Time.now - 180) > @last_pulse)
      pulse!
    end  
  end
end