Class: Fritzbox::Smarthome::Actor

Inherits:
Resource
  • Object
show all
Includes:
ActiveModel::Attributes, ActiveModel::Model
Defined in:
lib/fritzbox/smarthome/actor.rb

Direct Known Subclasses

Heater, Lightbulb, SmokeDetector, Switch

Constant Summary collapse

ResourceNotFound =
Class.new(RuntimeError)

Constants inherited from Resource

Resource::AuthenticationError

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Resource

get, parse

Class Method Details

.all(types: ['group', 'device']) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/fritzbox/smarthome/actor.rb', line 18

def all(types: ['group', 'device'])
  xml = parse(get(command: 'getdevicelistinfos'))

  Array.wrap(types.map { |type| xml.dig('devicelist', type) }.flatten).compact.map do |data|
    klass = Actor.descendants.find { |k| k.match?(data) } || Actor
    self.in?([klass, Actor]) ? klass.new_from_api(data) : nil
  end.compact
end

.find_by!(ain: nil) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/fritzbox/smarthome/actor.rb', line 27

def find_by!(ain: nil)
  data = parse(get(command: 'getdeviceinfos', ain: ain)).fetch('device')
  klass = Actor.descendants.find { |k| k.match?(data) } || Actor

  instance = klass.new(ain: ain)
  instance.assign_from_api(data)
  instance
rescue KeyError
  raise ResourceNotFound, "Unable to find actor with ain='#{ain}'"
end

.new_from_api(data) ⇒ Object



38
39
40
41
42
# File 'lib/fritzbox/smarthome/actor.rb', line 38

def new_from_api(data)
  instance = new
  instance.assign_from_api(data)
  instance
end

Instance Method Details

#assign_from_api(data) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
# File 'lib/fritzbox/smarthome/actor.rb', line 45

def assign_from_api(data)
  assign_attributes(
    id:            data.dig('@id').to_s,
    type:          data.dig('groupinfo').present? ? :group : :device,
    ain:           data.dig('@identifier').to_s,
    present:       data.dig('present') == '1',
    name:          (data.dig('name') || data.dig('@productname')).to_s,
    manufacturer:  (data.dig('manufacturer') || data.dig('@manufacturer')).to_s,
    group_members: data.dig('groupinfo', 'members').to_s.split(',').presence
  )
end

#reloadObject



57
58
59
60
61
62
63
# File 'lib/fritzbox/smarthome/actor.rb', line 57

def reload
  xml = parse(get(command: 'getdeviceinfos', ain: ain))
  assign_from_api(xml.fetch('device'))
  self
rescue KeyError
  raise ResourceNotFound, "Unable to reload actor with ain='#{ain}'"
end