Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import requests
import json
import sys
import time
timer = {}
hub_url = "192.168.1.2"
hours_to_refresh_token = 8
class ZWaveController(object):
timer = {}
token = ""
token_time = time.time()
seconds_to_refresh_token = 60*60*hours_to_refresh_token
def _make_header(self):
if self.token == "" or time.time() - self.token_time > self.seconds_to_refresh_token:
self.token = self._get_new_token()
token_time = time.time()
headers = {
'Authorization': "Token " + self.token
}
return headers
def _get_new_token(self):
url = "http://%s/api/tokenauth" % hub_url
data = {"username":"admin","password":"admin"}
response = requests.post(url, json=data)
token = response.json()['responseObject']
return token
def get_devices(self):
"""
Returns dictionary of all device data
"""
url = "http://%s/api/devices" % hub_url
headers = self._make_header()
response = requests.get(url, headers=headers, allow_redirects=False)
return response.json()['responseObject']
def get_device(self, node_id):
"""
Returns status data of a single device
"""
url = "http://%s/api/device/%s" % (hub_url, node_id)
headers = self._make_header()
response = requests.get(url, headers=headers, allow_redirects=False)
return response.json()['responseObject']
def get_level(self, node_id):
"""
Returns the level of a single device
"""
obj = self.get_device(node_id)
return obj['level']
def set_level(self, node_id, level):
"""
Sets the level of a single device.
Rate-limited to one query per second.
"""
if node_id in self.timer.keys():
gap = time.time() - self.timer[node_id]
if gap < 1:
time.sleep(1 - gap)
url = "http://%s/api/setdevicelevel/%s/%f" % (hub_url, node_id, level)
headers = self._make_header()
response = requests.post(url, headers=headers, allow_redirects=False)
self.timer[node_id] = time.time()
return response.json()['responseObject']['level']
if __name__ == "__main__":
import time
z = ZWaveController()
print z.get_devices()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment