-
Notifications
You must be signed in to change notification settings - Fork 1
/
smartthings.py
294 lines (253 loc) · 8.01 KB
/
smartthings.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
#
# smartthings.py
#
# David Janes
# IOTDB.org
# 2014-01-31
#
# Demonstrate how to use the SmartThings API from Python.
#
# See also:
# Example App explanation:
# http://build.smartthings.com/blog/tutorial-creating-a-custom-rest-smartapp-endpoint/
#
# Example PHP code:
# https://www.dropbox.com/s/7m7gmlr9q3u7rmk/exampleOauth.php
#
# Example "Groovy"/SMART code (this is the app we tap into)
# https://www.dropbox.com/s/lohzziy2wjlrppb/endpointExample.groovy
#
import sys
import requests
import pprint
import json
## import httplib
## httplib.HTTPConnection.debuglevel = 1
from optparse import OptionParser
try:
import iotdb_log
except:
class iotdb_log(object):
@staticmethod
def log(**ad):
pprint.pprint(ad)
class SmartThings(object):
def __init__(self, verbose=True):
self.verbose = verbose
self.std = {}
self.endpointd = {}
self.deviceds = {}
def load_settings(self, filename="smartthings.json"):
"""Load the JSON Settings file.
See the documentation, but briefly you can
get it from here:
https://iotdb.org/playground/oauthorize
"""
with open(filename) as fin:
self.std = json.load(fin)
def request_endpoints(self):
"""Get the endpoints exposed by the SmartThings App
The first command you need to call
"""
endpoints_url = self.std["api"]
endpoints_paramd = {
"access_token": self.std["access_token"]
}
endpoints_response = requests.get(url=endpoints_url, params=endpoints_paramd)
self.endpointd = endpoints_response.json()[0]
if self.verbose: iotdb_log.log(
"endpoints",
endpoints_url=endpoints_url,
endpoints_paramd=endpoints_paramd,
resultds=self.endpointd,
)
def request_devices(self, device_type):
"""List the devices"""
devices_url = "https://graph.api.smartthings.com%s/%s" % ( self.endpointd["url"], device_type, )
devices_paramd = {
}
devices_headerd = {
"Authorization": "Bearer %s" % self.std["access_token"],
}
devices_response = requests.get(url=devices_url, params=devices_paramd, headers=devices_headerd)
self.deviceds = devices_response.json()
for switchd in self.deviceds:
switchd['url'] = "%s/%s" % ( devices_url, switchd['id'], )
if self.verbose: iotdb_log.log(
"devices",
url=devices_url,
paramd=devices_paramd,
deviceds=self.deviceds,
)
return self.deviceds
def device_request(self, deviced, requestd):
"""Send a request the named device"""
command_url = deviced['url']
command_paramd = {
"access_token": self.std["access_token"]
}
command_headerd = {}
command_response = requests.put(
url=command_url,
params=command_paramd,
headers=command_headerd,
data=json.dumps(requestd)
)
def rest_request(self,rest_request, parameters):
if not parameters or parameters==None or parameters=="":
parameters = []
elif type(parameters)==type(""):
parameters = json.loads(parameters)
rest_url = "https://graph.api.smartthings.com%s/%s" % ( self.endpointd["url"], rest_request, )
rest_paramd = parameters
rest_headerd = {
"Authorization": "Bearer %s" % self.std["access_token"],
}
rest_response = requests.get(url=rest_url, params=rest_paramd, headers=rest_headerd)
rest_payload = rest_response.json()
return rest_payload
def cli():
dtypes = [
"switch", "motion", "presence", "acceleration", "contact",
"temperature", "battery", "acceleration", "threeAxis",
]
parser = OptionParser()
parser.add_option(
"", "--debug",
default = False,
action = "store_true",
dest = "debug",
help = "",
)
parser.add_option(
"", "--verbose",
default = False,
action = "store_true",
dest = "verbose",
help = "",
)
parser.add_option(
"", "--type",
dest = "device_type",
help = "The device type (required), one of %s" % ", ".join(dtypes)
)
parser.add_option(
"", "--id",
dest = "device_id",
help = "The ID or Name of the device to manipulate"
)
parser.add_option(
"", "--request",
dest = "request",
help = "Something to do, e.g. 'switch=1', 'switch=0'"
)
parser.add_option(
"", "--rest",
dest = "rest_request",
help = "Issue a rest request to the smartthings app"
)
parser.add_option(
"", "--rest_param",
dest = "rest_param",
help = "holds rest call parameters"
)
(options, args) = parser.parse_args()
if not options.rest_request and not options.device_type:
print >> sys.stderr, "%s: --type <%s>" % ( sys.argv[0], "|".join(dtypes))
parser.print_help(sys.stderr)
sys.exit(1)
st = SmartThings(verbose=options.verbose)
st.load_settings()
st.request_endpoints()
if options.rest_request:
pprint.pprint( st.rest_request(options.rest_request, options.rest_param))
else:
ds = st.request_devices(options.device_type)
if options.device_id:
ds = filter(lambda d: options.device_id in [ d.get("id"), d.get("label"), ], ds)
if options.request:
key, value = options.request.split('=', 2)
try:
value = int(value)
except ValueError:
pass
requestd = {
key: value
}
for d in ds:
iotdb_log.log(device=d, request=requestd)
st.device_request(d, requestd)
else:
print json.dumps(ds, indent=2, sort_keys=True)
if __name__ == '__main__':
# dtypes = [
# "switch", "motion", "presence", "acceleration", "contact",
# "temperature", "battery", "acceleration", "threeAxis",
# ]
#
# parser = OptionParser()
# parser.add_option(
# "", "--debug",
# default = False,
# action = "store_true",
# dest = "debug",
# help = "",
# )
# parser.add_option(
# "", "--verbose",
# default = False,
# action = "store_true",
# dest = "verbose",
# help = "",
# )
# parser.add_option(
# "", "--type",
# dest = "device_type",
# help = "The device type (required), one of %s" % ", ".join(dtypes)
# )
# parser.add_option(
# "", "--id",
# dest = "device_id",
# help = "The ID or Name of the device to manipulate"
# )
# parser.add_option(
# "", "--request",
# dest = "request",
# help = "Something to do, e.g. 'switch=1', 'switch=0'"
# )
#
# (options, args) = parser.parse_args()
#
# if not options.device_type:
# print >> sys.stderr, "%s: --type <%s>" % ( sys.argv[0], "|".join(dtypes))
# parser.print_help(sys.stderr)
# sys.exit(1)
#
#
# st = SmartThings(verbose=options.verbose)
# st.load_settings()
# st.request_endpoints()
#
# ds = st.request_devices(options.device_type)
#
# if options.device_id:
# ds = filter(lambda d: options.device_id in [ d.get("id"), d.get("label"), ], ds)
#
# if options.request:
# key, value = options.request.split('=', 2)
# try:
# value = int(value)
# except ValueError:
# pass
#
# requestd = {
# key: value
# }
#
# for d in ds:
# iotdb_log.log(device=d, request=requestd)
# st.device_request(d, requestd)
#
# else:
# print json.dumps(ds, indent=2, sort_keys=True)
cli()