Class: Huebot::DeviceMapper

Inherits:
Object
  • Object
show all
Defined in:
lib/huebot/device_mapper.rb

Constant Summary collapse

Unmapped =
Class.new(Error)

Instance Method Summary collapse

Constructor Details

#initialize(bridge, inputs = []) ⇒ DeviceMapper

Returns a new instance of DeviceMapper.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/huebot/device_mapper.rb', line 5

def initialize(bridge, inputs = [])
  all_lights, all_groups = bridge.lights, bridge.groups

  @lights_by_id = all_lights.reduce({}) { |a, l| a[l.id] = l; a }
  @lights_by_name = all_lights.reduce({}) { |a, l| a[l.name] = l; a }
  @groups_by_id = all_groups.reduce({}) { |a, g| a[g.id] = g; a }
  @groups_by_name = all_groups.reduce({}) { |a, g| a[g.name] = g; a }
  @devices_by_var = inputs.each_with_index.each_with_object({}) { |(x, idx), obj|
    obj[idx + 1] =
      case x
      when Light::Input then @lights_by_id[x.val.to_i] || @lights_by_name[x.val]
      when Group::Input then @groups_by_id[x.val.to_i] || @groups_by_name[x.val]
      else raise Error, "Invalid input: #{x}"
      end || raise(Unmapped, "Could not find #{x.class.name[8..-6].downcase} with id or name '#{x.val}'")
  }
  @all = @devices_by_var.values
end

Instance Method Details

#eachObject



23
24
25
26
27
28
29
# File 'lib/huebot/device_mapper.rb', line 23

def each
  if block_given?
    @all.each { |device| yield device }
  else
    @all.each
  end
end

#group!(id) ⇒ Object



35
36
37
# File 'lib/huebot/device_mapper.rb', line 35

def group!(id)
  @groups_by_id[id] || @groups_by_name[id] || (raise Unmapped, "Unmapped group '#{id}'")
end

#light!(id) ⇒ Object



31
32
33
# File 'lib/huebot/device_mapper.rb', line 31

def light!(id)
  @lights_by_id[id] || @lights_by_name[id] || (raise Unmapped, "Unmapped light '#{id}'")
end

#missing_groups(names) ⇒ Object



52
53
54
# File 'lib/huebot/device_mapper.rb', line 52

def missing_groups(names)
  names - @groups_by_name.keys
end

#missing_lights(names) ⇒ Object



48
49
50
# File 'lib/huebot/device_mapper.rb', line 48

def missing_lights(names)
  names - @lights_by_name.keys
end

#missing_vars(vars) ⇒ Object



56
57
58
59
60
61
62
63
# File 'lib/huebot/device_mapper.rb', line 56

def missing_vars(vars)
  missing = vars - @devices_by_var.keys
  if @all.any?
    missing - [:all]
  else
    missing
  end
end

#var!(id) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/huebot/device_mapper.rb', line 39

def var!(id)
  case id
  when :all
    @all
  else
    @devices_by_var[id] || (raise Unmapped, "Unmapped device '#{id}'")
  end
end