Debian Codegraph @

renson_endura_delta/renson.py

raw symbols SCIP
1 """Main class of the Renson ventilation library."""
2 import json
3 import logging
4 from datetime import datetime
5 import re
6
7 import requests
8
9 from renson_endura_delta.field_enum import FILTER_PRESET_FIELD, FieldEnum, FIRMWARE_VERSION, FIRMWARE_VERSION_FIELD
10 from renson_endura_delta.general_enum import (Level, Quality,
11 ServiceNames, DataType, Level)
12
13 _LOGGER = logging.getLogger(__name__)
14
15
16 class ValueData:
17 """Class for getting Renson data."""
18
19 def __init__(self, value):
20 """Construct the class."""
21 self.Value = value
22
23
24 class RensonVentilation:
25 """Main class to get data and post data to the Renson unit."""
26
27 data_url = "http://[host]/JSON/ModifiedItems?wsn=150324488709"
28 service_url = "http://[host]/JSON/Vars/[field]?index0=0&index1=0&index2=0"
29 firmware_server_url = "http://www.renson-app.com/endura_delta/firmware/check.php"
30 firmware_dowload_url = "http://www.renson-app.com/endura_delta/firmware/files/"
31
32 host = None
33
34 def __init__(self, host: str):
35 """Initialize Renson Ventilation class by giving the host name or ip address."""
36 self.host = host
37
38 def connect(self) -> bool:
39 try:
40 response = requests.get(self.data_url.replace("[host]", self.host))
41
42 return response.status_code == 200
43 except Exception:
44 return False
45
46 def get_all_data(self):
47 response = requests.get(self.data_url.replace("[host]", self.host))
48
49 if response.status_code == 200:
50 return response.json()
51 else:
52 _LOGGER.error(f"Error communicating with API: {response.status_code}")
53 return ''
54
55 def get_field_value(self, all_data, fieldname: str) -> str:
56 """Search for the field in the Reson JSON and return the value of it."""
57 for data in all_data["ModifiedItems"]:
58 if data["Name"] == fieldname == FIRMWARE_VERSION_FIELD.name:
59 return data["Value"].split()[-1]
60 elif data["Name"] == fieldname:
61 return data["Value"]
62 return ''
63
64 def parse_value(self, value, data_type):
65 """Parse value to correct type"""
66 if data_type == DataType.NUMERIC:
67 return self.parse_numeric(value)
68 elif data_type == DataType.STRING:
69 return value
70 elif data_type == DataType.LEVEL:
71 return self.parse_data_level(value).value
72 elif data_type == DataType.BOOLEAN:
73 return self.parse_boolean(value)
74 elif data_type == DataType.QUALITY:
75 return self.parse_quality(value).value
76
77 def __get_service_url(self, field: ServiceNames):
78 """Make the full url of the Renson API and return it."""
79 return self.service_url.replace("[host]", self.host).replace(
80 "[field]", field.value.replace(" ", "%20")
81 )
82
83 def __get_base_url(self, path: str):
84 """Make the base url of the Renson API and return it."""
85 return "http://" + self.host + path
86
87
88 def parse_numeric(self, value: str) -> float:
89 """Get the value of the field and convert it to a numeric type."""
90 return round(float(value))
91
92 def parse_data_level(self, value: str) -> Level:
93 """Get the value of the field and convert it to a Level type."""
94 return Level[value.split()[-1].upper()]
95
96 def parse_boolean(self, value: str) -> bool:
97 """Get the value of the field and convert it to a boolean type."""
98 return bool(int(value))
99
100 def parse_quality(self, value: str) -> Quality:
101 """Get the value of the field and convert it to a Quality type."""
102 value = round(float(value))
103 if value < 950:
104 return Quality.GOOD
105 elif value < 1500:
106 return Quality.POOR
107 else:
108 return Quality.BAD
109
110 def set_manual_level(self, level: Level):
111 """Set the manual level of the Renson unit. When set to 'Off' the unit will go back to auto program."""
112 data = ValueData(level.value)
113
114 response = requests.post(
115 self.__get_service_url(ServiceNames.SET_MANUAL_LEVEL_FIELD), data=json.dumps(data.__dict__)
116 )
117
118 if response.status_code != 200:
119 _LOGGER.error("Ventilation unit did not return 200")
120
121 def restart_device(self):
122 """Restart device"""
123 response = requests.post(
124 self.__get_base_url("/Reset")
125 )
126
127 if response.status_code != 200:
128 _LOGGER.error("Ventilation unit did not return 200")
129
130 def sync_time(self):
131 """Sync time of the Renson unit to current date and time."""
132 response = requests.get(self.__get_service_url(ServiceNames.TIME_AND_DATE_FIELD))
133
134 if response.status_code == 200:
135 json_result = response.json()
136 device_time = datetime.strptime(
137 json_result["Value"], "%d %b %Y %H:%M"
138 )
139 current_time = datetime.now()
140
141 if current_time != device_time:
142 data = ValueData(current_time.strftime("%d %b %Y %H:%M").lower())
143 requests.post(
144 self.__get_service_url(ServiceNames.TIME_AND_DATE_FIELD), data=json.dumps(data.__dict__)
145 )
146 else:
147 _LOGGER.error("Ventilation unit did not return 200")
148
149 def set_timer_level(self, level: Level, time: int):
150 """Set a level for a specific time (in minutes)."""
151
152 if level == Level.OFF:
153 raise Exception("Off is not a valid type for setting manual level")
154
155 data = ValueData(str(time) + " min " + level.value)
156 response = requests.post(self.__get_service_url(ServiceNames.TIMER_FIELD), data=json.dumps(data.__dict__))
157
158 if response.status_code != 200:
159 _LOGGER.error("Ventilation unit did not return 200")
160
161 def set_breeze(self, level: Level, temperature: int, activated: bool):
162 """Activate/deactivate breeze feature and give breeze parameters to the function."""
163
164 if level == Level.HOLIDAY or level == Level.OFF or level == Level.BREEZE:
165 raise Exception("Holiday, Off, Breeze are not a valid types for setting breeze level")
166
167 data = ValueData(str(level.value))
168 response = requests.post(
169 self.__get_service_url(ServiceNames.BREEZE_LEVEL_FIELD), data=json.dumps(data.__dict__)
170 )
171
172 if response.status_code != 200:
173 _LOGGER.error("Ventilation unit did not return 200")
174
175 data = ValueData(str(temperature))
176 response = requests.post(
177 self.__get_service_url(ServiceNames.BREEZE_TEMPERATURE_FIELD), data=json.dumps(data.__dict__)
178 )
179
180 if response.status_code != 200:
181 _LOGGER.error("Ventilation unit did not return 200")
182
183 data = ValueData(str(int(activated)))
184 response = requests.post(
185 self.__get_service_url(ServiceNames.BREEZE_ENABLE_FIELD), data=json.dumps(data.__dict__)
186 )
187
188 if response.status_code != 200:
189 _LOGGER.error("Ventilation unit did not return 200")
190
191 def set_day_time(self, day: str):
192 """Set day time for the device."""
193 data = ValueData(day)
194 response = requests.post(self.__get_service_url(ServiceNames.DAYTIME_FIELD), data=json.dumps(data.__dict__))
195
196 if response.status_code != 200:
197 _LOGGER.error("Start daytime cannot be set")
198
199 def set_night_time(self, night: str):
200 """Set night time for the device."""
201 data = ValueData(night)
202 response = requests.post(self.__get_service_url(ServiceNames.NIGHTTIME_FIELD), data=json.dumps(data.__dict__))
203
204 if response.status_code != 200:
205 _LOGGER.error("Start nighttime cannot be set")
206
207 def set_pollution(self, day: Level, night: Level, humidity_control: bool,
208 airquality_control: bool,
209 co2_control: bool, co2_threshold: bool, co2_hysteresis: bool):
210 """Enable/disable special auto features of the Renson unit."""
211
212 if day == Level.HOLIDAY or day == Level.OFF or day == Level.BREEZE:
213 raise Exception("Holiday, Off, Breeze are not a valid types for setting day level")
214
215 if night == Level.HOLIDAY or night == Level.OFF or night == Level.BREEZE:
216 raise Exception("Holiday, Off, Breeze are not a valid types for setting night level")
217
218 data = ValueData(str(day.value))
219 response = requests.post(
220 self.__get_service_url(ServiceNames.DAY_POLLUTION_FIELD), data=json.dumps(data.__dict__)
221 )
222
223 if response.status_code != 200:
224 _LOGGER.error("Ventilation unit did not return 200")
225
226 data = ValueData(str(night.value))
227 response = requests.post(
228 self.__get_service_url(ServiceNames.NIGHT_POLLUTION_FIELD), data=json.dumps(data.__dict__)
229 )
230
231 if response.status_code != 200:
232 _LOGGER.error("Ventilation unit did not return 200")
233
234 data = ValueData(str(int(humidity_control)))
235 response = requests.post(
236 self.__get_service_url(ServiceNames.HUMIDITY_CONTROL_FIELD), data=json.dumps(data.__dict__)
237 )
238
239 if response.status_code != 200:
240 _LOGGER.error("Ventilation unit did not return 200")
241
242 data = ValueData(str(int(airquality_control)))
243 response = requests.post(
244 self.__get_service_url(ServiceNames.AIR_QUALITY_CONTROL_FIELD), data=json.dumps(data.__dict__)
245 )
246
247 if response.status_code != 200:
248 _LOGGER.error("Ventilation unit did not return 200")
249
250 data = ValueData(str(int(co2_control)))
251 response = requests.post(
252 self.__get_service_url(ServiceNames.CO2_CONTROL_FIELD), data=json.dumps(data.__dict__)
253 )
254
255 if response.status_code != 200:
256 _LOGGER.error("Ventilation unit did not return 200")
257
258 data = ValueData(str(int(co2_threshold)))
259 response = requests.post(
260 self.__get_service_url(ServiceNames.CO2_THRESHOLD_FIELD), data=json.dumps(data.__dict__)
261 )
262
263 if response.status_code != 200:
264 _LOGGER.error("Ventilation unit did not return 200")
265
266 data = ValueData(str(int(co2_hysteresis)))
267 response = requests.post(
268 self.__get_service_url(ServiceNames.CO2_HYSTERESIS_FIELD), data=json.dumps(data.__dict__)
269 )
270
271 if response.status_code != 200:
272 _LOGGER.error("Ventilation unit did not return 200")
273
274 def set_filter_days(self, days: int):
275 """Set the filter days."""
276 data = ValueData(str(int(days)))
277 response = requests.post(
278 self.__get_service_url(ServiceNames.FILTER_DAYS_FIELD), data=json.dumps(data.__dict__)
279 )
280
281 if response.status_code != 200:
282 _LOGGER.error("Ventilation unit did not return 200")
283
284 def set_remaining_filter_days(self, days: int):
285 """Set the remaining filter days."""
286 data = ValueData(str(int(days)))
287 response = requests.post(
288 self.__get_service_url(ServiceNames.FILTER_REMAIN_FIELD), data=json.dumps(data.__dict__)
289 )
290
291 if response.status_code != 200:
292 _LOGGER.error("Ventilation unit did not return 200")
293
294 def is_firmware_up_to_date(self, current_version) -> bool:
295 """Check if the Renson firmware is up to date."""
296 # version = self.get_field_value(FIRMWARE_VERSION).split()[-1]
297 version = current_version.split()[-1]
298 json_string = '{"a":"check", "name":"D_' + version + '.fuf"}'
299
300 response_server = requests.post(self.firmware_server_url, data=json_string)
301 if response_server.status_code == 200:
302 return bool((response_server.json())["latest"])
303
304 return False
305
306 def get_latest_firmware_version(self) -> str:
307 """Get the latest Renson firmware version."""
308 json_string = '{"a":"check", "name":"D_0.fuf"}'
309
310 response_server = requests.post(self.firmware_server_url, data=json_string)
311
312 if response_server.status_code == 200:
313 return re.sub(r"D_(.*)\.fuf", r"\1", response_server.json()["url"])
314
315 return ""
316
317 def reset_filter(self):
318 """Reset filter timer"""
319 data = self.get_all_data()
320 filter_preset = self.parse_numeric(self.get_field_value(data, FILTER_PRESET_FIELD.name))
321 self.set_remaining_filter_days(filter_preset)
322
323