Class: Hass::Domain

Inherits:
Object
  • Object
show all
Defined in:
lib/hass/domain.rb

Overview

Base class for all domains (lights, switches, media_player…)

Constant Summary collapse

DATA =

Just to make sure, the constant exists

{}.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(entity_id) ⇒ Domain

Returns a new instance of Domain.



10
11
12
# File 'lib/hass/domain.rb', line 10

def initialize(entity_id)
  @entity_id = entity_id
end

Instance Attribute Details

#clientObject

Returns the value of attribute client.



4
5
6
# File 'lib/hass/domain.rb', line 4

def client
  @client
end

#entity_idObject (readonly)

Returns the value of attribute entity_id.



5
6
7
# File 'lib/hass/domain.rb', line 5

def entity_id
  @entity_id
end

Instance Method Details

#attributesObject



47
48
49
# File 'lib/hass/domain.rb', line 47

def attributes
  state_data['attributes']
end

#check_params(method_name, given_params) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/hass/domain.rb', line 18

def check_params(method_name, given_params)
  required_fields(method_name).each do |required_field|
    next if given_params.key?(required_field)

    raise "Parameter #{required_field} might be missing. #{method_help(method_name)}"
  end
end

#dataObject



55
56
57
# File 'lib/hass/domain.rb', line 55

def data
  self.class.const_get('DATA')
end

#execute_service(service, params = {}) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/hass/domain.rb', line 35

def execute_service(service, params = {})
  params['entity_id'] = @entity_id
  @client.post("/services/#{data['domain']}/#{service}", params)
rescue RuntimeError => error
  puts "Rescuing from #{error.class}: #{error}"
  check_params(service, params)
end

#method_help(method_name) ⇒ Object

Returns a method description as a help text



27
28
29
30
31
32
33
# File 'lib/hass/domain.rb', line 27

def method_help(method_name)
  param_help = required_fields(method_name).map { |name| "#{name}: #{name}_value" }
  method_hint = "#{method_name}(#{param_help.join(', ')})"
  fields = data['services'][method_name]['fields']
  method_description = fields.keys.map { |field| "#{field}: #{fields[field]['description']}" }.join("\n")
  "Hint: you can call this method with #{method_hint}\n#{method_description}"
end

#required_fields(method_name) ⇒ Object



14
15
16
# File 'lib/hass/domain.rb', line 14

def required_fields(method_name)
  data['services'][method_name]['fields'].keys.reject { |name| name == 'entity_id' }
end

#stateObject



51
52
53
# File 'lib/hass/domain.rb', line 51

def state
  state_data['state']
end

#state_dataObject



43
44
45
# File 'lib/hass/domain.rb', line 43

def state_data
  @client.get("/states/#{@entity_id}")
end