Class: Wemo::Switch

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

Constant Summary collapse

ROUTE =
"/upnp/control/basicevent1"

Instance Method Summary collapse

Constructor Details

#initialize(endpoint) ⇒ Switch

Returns a new instance of Switch.



11
12
13
# File 'lib/wemo_switch.rb', line 11

def initialize(endpoint)
  @endpoint = endpoint
end

Instance Method Details

#_config_dirObject



49
50
51
# File 'lib/wemo_switch.rb', line 49

def _config_dir
  File.join(_root, "config")
end

#_outlet_endpoint(port) ⇒ Object



57
58
59
# File 'lib/wemo_switch.rb', line 57

def _outlet_endpoint(port)
  "http://" + @endpoint + ":" + port.to_s + ROUTE
end

#_rootObject



45
46
47
# File 'lib/wemo_switch.rb', line 45

def _root
  File.dirname(__dir__)
end

#_try_all_portsObject



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/wemo_switch.rb', line 33

def _try_all_ports
  [49151, 49153, 49154].each do |port|
    begin
      client = Savon.client(:wsdl => _wsdl, :endpoint => _outlet_endpoint(port), :open_timeout => 0.5, :read_timeout => 0.5)
      yield client
    rescue Net::ReadTimeout, Errno::ECONNREFUSED
      next
    end
  end
  raise "Couldn't connect..."
end

#_wsdlObject



53
54
55
# File 'lib/wemo_switch.rb', line 53

def _wsdl
  File.join(_config_dir, YAML.load_file(File.join(_config_dir, "wemo.yml"))['wsdl'])
end

#get_stateObject



25
26
27
28
29
30
31
# File 'lib/wemo_switch.rb', line 25

def get_state
  _try_all_ports do |client|
    response = client.call(:get_binary_state)
    state = response.body[:get_binary_state_response][:binary_state]
    return state == "1"
  end
end

#toggle_outletObject



15
16
17
18
19
20
21
22
23
# File 'lib/wemo_switch.rb', line 15

def toggle_outlet
  _try_all_ports do |client|
    response = client.call(:get_binary_state)
    state = response.body[:get_binary_state_response][:binary_state]
    state = state == "1" ? "0" : "1"
    client.call(:set_binary_state, :message => {"BinaryState" => state})
    return true
  end
end