forked from mariusz-ostoja-swierczynski/tech-controllers
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tech.py
198 lines (174 loc) · 7.17 KB
/
tech.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
"""
Python wrapper for getting interaction with Tech devices.
"""
import logging
import aiohttp
import json
import time
import asyncio
logging.basicConfig(level=logging.DEBUG)
_LOGGER = logging.getLogger(__name__)
class Tech:
"""Main class to perform Tech API requests"""
TECH_API_URL = "https://emodul.eu/api/v1/"
def __init__(self, session: aiohttp.ClientSession, user_id = None, token = None, base_url = TECH_API_URL, update_interval = 30):
_LOGGER.debug("Init Tech")
self.headers = {
'Accept': 'application/json',
'Accept-Encoding': 'gzip'
}
self.base_url = base_url
self.update_interval = update_interval
self.session = session
if user_id and token:
self.user_id = user_id
self.token = token
self.headers.setdefault("Authorization", "Bearer " + token)
self.authenticated = True
else:
self.authenticated = False
self.last_update = None
self.update_lock = asyncio.Lock()
self.zones = {}
async def get(self, request_path):
url = self.base_url + request_path
_LOGGER.debug("Sending GET request: " + url)
async with self.session.get(url, headers=self.headers) as response:
if response.status != 200:
_LOGGER.warning("Invalid response from Tech API: %s", response.status)
raise TechError(response.status, await response.text())
data = await response.json()
_LOGGER.debug(data)
return data
async def post(self, request_path, post_data):
url = self.base_url + request_path
_LOGGER.debug("Sending POST request: " + url)
async with self.session.post(url, data=post_data, headers=self.headers) as response:
if response.status != 200:
_LOGGER.warning("Invalid response from Tech API: %s", response.status)
raise TechError(response.status, await response.text())
data = await response.json()
_LOGGER.debug(data)
return data
async def authenticate(self, username, password):
path = "authentication"
post_data = '{"username": "' + username + '", "password": "' + password + '"}'
result = await self.post(path, post_data)
self.authenticated = result["authenticated"]
if self.authenticated:
self.user_id = str(result["user_id"])
self.token = result["token"]
self.headers = {
'Accept': 'application/json',
'Accept-Encoding': 'gzip',
'Authorization': 'Bearer ' + self.token
}
return result["authenticated"]
async def list_modules(self):
if self.authenticated:
path = "users/" + self.user_id + "/modules"
result = await self.get(path)
else:
raise TechError(401, "Unauthorized")
return result
async def get_module_data(self, module_udid):
_LOGGER.debug("Getting module data..." + module_udid + ", " + self.user_id)
if self.authenticated:
path = "users/" + self.user_id + "/modules/" + module_udid
result = await self.get(path)
else:
raise TechError(401, "Unauthorized")
return result
async def get_module_zones(self, module_udid):
"""Returns Tech module zones either from cache or it will
update all the cached values for Tech module assuming
no update has occurred for at least the [update_interval].
Parameters:
inst (Tech): The instance of the Tech API.
module_udid (string): The Tech module udid.
Returns:
Dictionary of zones indexed by zone ID.
"""
async with self.update_lock:
now = time.time()
_LOGGER.debug("Geting module zones: now: %s, last_update %s, interval: %s", now, self.last_update, self.update_interval)
if self.last_update is None or now > self.last_update + self.update_interval:
_LOGGER.debug("Updating module zones cache..." + module_udid)
result = await self.get_module_data(module_udid)
zones = result["zones"]["elements"]
zones = list(filter(lambda e: e['zone']['zoneState'] != "zoneUnregistered", zones))
for zone in zones:
self.zones[zone["zone"]["id"]] = zone
self.last_update = now
return self.zones
async def get_zone(self, module_udid, zone_id):
"""Returns zone from Tech API cache.
Parameters:
module_udid (string): The Tech module udid.
zone_id (int): The Tech module zone ID.
Returns:
Dictionary of zone.
"""
await self.get_module_zones(module_udid)
return self.zones[zone_id]
async def set_const_temp(self, module_udid, zone_id, target_temp):
"""Sets constant temperature of the zone.
Parameters:
module_udid (string): The Tech module udid.
zone_id (int): The Tech module zone ID.
target_temp (float): The target temperature to be set within the zone.
Returns:
JSON object with the result.
"""
_LOGGER.debug("Setting zone constant temperature...")
if self.authenticated:
path = "users/" + self.user_id + "/modules/" + module_udid + "/zones"
data = {
"mode" : {
"id" : self.zones[zone_id]["mode"]["id"],
"parentId" : zone_id,
"mode" : "constantTemp",
"constTempTime" : 60,
"setTemperature" : int(target_temp * 10),
"scheduleIndex" : 0
}
}
_LOGGER.debug(data)
result = await self.post(path, json.dumps(data))
_LOGGER.debug(result)
else:
raise TechError(401, "Unauthorized")
return result
async def set_zone(self, module_udid, zone_id, on = True):
"""Turns the zone on or off.
Parameters:
module_udid (string): The Tech module udid.
zone_id (int): The Tech module zone ID.
on (bool): Flag indicating to turn the zone on if True or off if False.
Returns:
JSON object with the result.
"""
_LOGGER.debug("Turing zone on/off: %s", on)
if self.authenticated:
path = "users/" + self.user_id + "/modules/" + module_udid + "/zones"
data = {
"zone" : {
"id" : zone_id,
"zoneState" : "zoneOn" if on else "zoneOff"
}
}
_LOGGER.debug(data)
result = await self.post(path, json.dumps(data))
_LOGGER.debug(result)
else:
raise TechError(401, "Unauthorized")
return result
class TechError(Exception):
"""Raised when Tech APi request ended in error.
Attributes:
status_code - error code returned by Tech API
status - more detailed description
"""
def __init__(self, status_code, status):
self.status_code = status_code
self.status = status