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(lights: [], groups: [], inputs: []) ⇒ DeviceMapper



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

def initialize(lights: [], groups:[], inputs: [])
  @lights_by_id = lights.each_with_object({}) { |l, a| a[l.id] = l }
  @lights_by_name = lights.each_with_object({}) { |l, a| a[l.name] = l }
  @groups_by_id = groups.each_with_object({}) { |g, a| a[g.id] = g }
  @groups_by_name = groups.each_with_object({}) { |g, a| a[g.name] = g }
  @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..-8].downcase} with id or name '#{x.val}'")
  }
  @all = @devices_by_var.values
end

Instance Method Details

#eachObject



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

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

#group!(id) ⇒ Object



33
34
35
# File 'lib/huebot/device_mapper.rb', line 33

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

#light!(id) ⇒ Object



29
30
31
# File 'lib/huebot/device_mapper.rb', line 29

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

#missing_groups(names) ⇒ Object



50
51
52
# File 'lib/huebot/device_mapper.rb', line 50

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

#missing_lights(names) ⇒ Object



46
47
48
# File 'lib/huebot/device_mapper.rb', line 46

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

#missing_vars(vars) ⇒ Object



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

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

#var!(id) ⇒ Object



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

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