/
smartthingr.rb
61 lines (48 loc) · 1.35 KB
/
smartthingr.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Smartthingr
attr_accessor :conn
def initialize(user)
@user = user
@token = user.authentication.oauth_token
@conn = Faraday.new
@conn.headers = {"Authorization" => "Bearer #{@token}"}
@base_url = "https://graph.api.smartthings.com"
get_apps
end
def get_apps
endpoint = "https://graph.api.smartthings.com/api/smartapps/endpoints"
r = @conn.get endpoint
if r.status == 200
body = JSON.parse r.body
if body.first
@st_url = body.first['url']
end
else
puts "BAD #{r}"
end
end
def get_switches
switches = JSON.parse @conn.get("#{@base_url}#{@st_url}/switch").body
end
def change_mode(command="Home")
result = @conn.post "#{@base_url}#{@st_url}/mode?command=#{command}"
end
def change_lights(command)
lights = @user.light_switches
if command == 'on'
lights = lights.where(turn_on: true)
else
lights = lights.where(turn_off: true)
end
lights.map(&:name).each do |light|
r = @conn.post "#{@base_url}#{@st_url}/switch?deviceId=#{light}&command=#{command}"
end
end
def change_single_switch(switch,command)
light = @user.light_switches.where("name ilike ?","%#{switch}%").first
if light
r = @conn.post "#{@base_url}#{@st_url}/switch?deviceId=#{light.name}&command=#{command}"
else
false
end
end
end