pyvesync 3.0.0b0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. pyvesync/__init__.py +11 -0
  2. pyvesync/base_devices/__init__.py +35 -0
  3. pyvesync/base_devices/bulb_base.py +348 -0
  4. pyvesync/base_devices/fan_base.py +398 -0
  5. pyvesync/base_devices/fryer_base.py +69 -0
  6. pyvesync/base_devices/humidifier_base.py +460 -0
  7. pyvesync/base_devices/outlet_base.py +315 -0
  8. pyvesync/base_devices/purifier_base.py +518 -0
  9. pyvesync/base_devices/switch_base.py +270 -0
  10. pyvesync/base_devices/thermostat_base.py +277 -0
  11. pyvesync/base_devices/vesyncbasedevice.py +580 -0
  12. pyvesync/const.py +749 -0
  13. pyvesync/device_container.py +360 -0
  14. pyvesync/device_map.py +1090 -0
  15. pyvesync/devices/__init__.py +1 -0
  16. pyvesync/devices/vesyncbulb.py +1254 -0
  17. pyvesync/devices/vesyncfan.py +238 -0
  18. pyvesync/devices/vesynchumidifier.py +785 -0
  19. pyvesync/devices/vesynckitchen.py +664 -0
  20. pyvesync/devices/vesyncoutlet.py +962 -0
  21. pyvesync/devices/vesyncpurifier.py +951 -0
  22. pyvesync/devices/vesyncswitch.py +449 -0
  23. pyvesync/devices/vesyncthermostat.py +175 -0
  24. pyvesync/models/__init__.py +11 -0
  25. pyvesync/models/base_models.py +117 -0
  26. pyvesync/models/bulb_models.py +173 -0
  27. pyvesync/models/bypass_models.py +264 -0
  28. pyvesync/models/fan_models.py +46 -0
  29. pyvesync/models/fryer_models.py +28 -0
  30. pyvesync/models/home_models.py +158 -0
  31. pyvesync/models/humidifier_models.py +187 -0
  32. pyvesync/models/outlet_models.py +194 -0
  33. pyvesync/models/purifier_models.py +204 -0
  34. pyvesync/models/switch_models.py +89 -0
  35. pyvesync/models/thermostat_models.py +122 -0
  36. pyvesync/models/vesync_models.py +252 -0
  37. pyvesync/utils/__init__.py +1 -0
  38. pyvesync/utils/colors.py +248 -0
  39. pyvesync/utils/device_mixins.py +366 -0
  40. pyvesync/utils/enum_utils.py +25 -0
  41. pyvesync/utils/errors.py +859 -0
  42. pyvesync/utils/helpers.py +696 -0
  43. pyvesync/utils/logs.py +500 -0
  44. pyvesync/vesync.py +445 -0
  45. pyvesync-3.0.0b0.dist-info/METADATA +527 -0
  46. pyvesync-3.0.0b0.dist-info/RECORD +49 -0
  47. pyvesync-3.0.0b0.dist-info/WHEEL +5 -0
  48. pyvesync-3.0.0b0.dist-info/licenses/LICENSE +21 -0
  49. pyvesync-3.0.0b0.dist-info/top_level.txt +1 -0
pyvesync/vesync.py ADDED
@@ -0,0 +1,445 @@
1
+ """VeSync API Device Libary."""
2
+
3
+ from __future__ import annotations
4
+ import logging
5
+ import asyncio
6
+ from typing import Self
7
+ from aiohttp import ClientSession
8
+ from aiohttp.client_exceptions import ClientResponseError
9
+ from mashumaro.mixins.orjson import DataClassORJSONMixin
10
+
11
+ from pyvesync.utils.helpers import Helpers
12
+ from pyvesync.const import API_BASE_URL, DEFAULT_REGION
13
+ from pyvesync.device_container import DeviceContainer, DeviceContainerInstance
14
+ from pyvesync.utils.logs import LibraryLogger
15
+ from pyvesync.models.vesync_models import (
16
+ RequestDeviceListModel,
17
+ ResponseDeviceListModel,
18
+ RequestLoginModel,
19
+ ResponseLoginModel
20
+ )
21
+ from pyvesync.utils.errors import (
22
+ ErrorCodes,
23
+ ErrorTypes,
24
+ VeSyncAPIResponseError,
25
+ VeSyncAPIStatusCodeError,
26
+ VeSyncError,
27
+ VeSyncServerError,
28
+ VesyncLoginError,
29
+ raise_api_errors,
30
+ )
31
+
32
+
33
+ logger = logging.getLogger(__name__)
34
+
35
+ API_RATE_LIMIT: int = 30
36
+ DEFAULT_TZ: str = 'America/New_York'
37
+
38
+ DEFAULT_ENER_UP_INT: int = 21600
39
+
40
+
41
+ class VeSync: # pylint: disable=function-redefined
42
+ """VeSync Manager Class."""
43
+
44
+ __slots__ = (
45
+ '__weakref__',
46
+ '_account_id',
47
+ '_close_session',
48
+ '_debug',
49
+ '_device_container',
50
+ '_redact',
51
+ '_token',
52
+ '_verbose',
53
+ 'country_code',
54
+ 'enabled',
55
+ 'in_process',
56
+ "language",
57
+ 'password',
58
+ 'session',
59
+ 'time_zone',
60
+ 'username'
61
+ )
62
+
63
+ def __init__(self,
64
+ username: str,
65
+ password: str,
66
+ session: ClientSession | None = None,
67
+ time_zone: str = DEFAULT_TZ) -> None:
68
+ """Initialize VeSync Manager.
69
+
70
+ This class is used as the manager for all VeSync objects, all methods and
71
+ API calls are performed from this class. Time zone, debug and redact are
72
+ optional. Time zone must be a string of an IANA time zone format. Once
73
+ class is instantiated, call `await manager.login()` to log in to VeSync servers,
74
+ which returns `True` if successful. Once logged in, call
75
+ `await manager.get_devices()` to retrieve devices. Then `await `manager.update()`
76
+ to update all devices or `await manager.devices[0].update()` to
77
+ update a single device.
78
+
79
+ Args:
80
+ username (str): VeSync account username (usually email address)
81
+ password (str): VeSync account password
82
+ session (ClientSession): aiohttp client session for
83
+ API calls, by default None
84
+ time_zone (str): Time zone for device from IANA database, by default
85
+ DEFAULT_TZ. This is automatically set to the time zone of the
86
+ VeSync account during login.
87
+
88
+ Attributes:
89
+ session (ClientSession): Client session for API calls
90
+ devices (DeviceContainer): Container for all VeSync devices,
91
+ has functionality of a mutable set. See
92
+ [`DeviceContainer`][pyvesync.device_container.DeviceContainer] for
93
+ more information
94
+ token (str): VeSync API token
95
+ account_id (str): VeSync account ID
96
+ country_code (str): Country code for VeSync account pulled from API
97
+ time_zone (str): Time zone for VeSync account pulled from API
98
+ enabled (bool): True if logged in to VeSync, False if not
99
+
100
+ Note:
101
+ This class is a context manager, use `async with VeSync() as manager:`
102
+ to manage the session context. The session will be closed when exiting
103
+ if no session is passed in.
104
+
105
+ The `manager.devices` attribute is a DeviceContainer object that contains
106
+ all VeSync devices. The `manager.devices` object has the functionality of
107
+ a set, and can be iterated over to access devices. See :obj:`DeviceContainer`
108
+ for more information.
109
+
110
+ If using a context manager is not convenient, `manager.__aenter__()` and
111
+ `manager.__aexit__()` can be called directly.
112
+
113
+ See Also:
114
+ :obj:`DeviceContainer`
115
+ Container object to store VeSync devices
116
+ :obj:`DeviceState`
117
+ Object to store device state information
118
+ """
119
+ self.session = session
120
+ self._close_session = False
121
+ self._debug = False
122
+ self._redact = True
123
+ if self._redact:
124
+ self.redact = self.redact
125
+ self.username: str = username
126
+ self.password: str = password
127
+ self._token: str | None = None
128
+ self._account_id: str | None = None
129
+ self.country_code: str = DEFAULT_REGION
130
+ self._verbose: bool = False
131
+ self.time_zone: str = time_zone
132
+ self.language: str = 'en'
133
+
134
+ self.enabled = False
135
+ self.in_process = False
136
+ self._device_container: DeviceContainer = DeviceContainerInstance
137
+
138
+ @property
139
+ def devices(self) -> DeviceContainer:
140
+ """Return VeSync device container.
141
+
142
+ See Also:
143
+ The pyvesync.device_container.DeviceContainer object
144
+ for methods and properties.
145
+ """
146
+ return self._device_container
147
+
148
+ @property
149
+ def token(self) -> str:
150
+ """Return VeSync API token."""
151
+ if self._token is None:
152
+ raise AttributeError('Token not set, run login() method')
153
+ return self._token
154
+
155
+ @property
156
+ def account_id(self) -> str:
157
+ """Return VeSync account ID."""
158
+ if self._account_id is None:
159
+ raise AttributeError('Account ID not set, run login() method')
160
+ return self._account_id
161
+
162
+ @property
163
+ def debug(self) -> bool:
164
+ """Return debug flag."""
165
+ return self._debug
166
+
167
+ @debug.setter
168
+ def debug(self, new_flag: bool) -> None:
169
+ """Set debug flag."""
170
+ if new_flag:
171
+ LibraryLogger.debug = True
172
+ LibraryLogger.configure_logger(logging.DEBUG)
173
+ else:
174
+ LibraryLogger.debug = False
175
+ LibraryLogger.configure_logger(logging.WARNING)
176
+ self._debug = new_flag
177
+
178
+ @property
179
+ def verbose(self) -> bool:
180
+ """Enable verbose logging."""
181
+ return LibraryLogger.verbose
182
+
183
+ @verbose.setter
184
+ def verbose(self, new_flag: bool) -> None:
185
+ """Set verbose logging."""
186
+ if new_flag:
187
+ LibraryLogger.verbose = True
188
+ LibraryLogger.configure_logger(logging.DEBUG)
189
+ else:
190
+ LibraryLogger.verbose = False
191
+ self._verbose = new_flag
192
+
193
+ @property
194
+ def redact(self) -> bool:
195
+ """Return debug flag."""
196
+ return self._redact
197
+
198
+ @redact.setter
199
+ def redact(self, new_flag: bool) -> None:
200
+ """Set debug flag."""
201
+ if new_flag:
202
+ LibraryLogger.shouldredact = True
203
+ elif new_flag is False:
204
+ LibraryLogger.shouldredact = False
205
+ self._redact = new_flag
206
+
207
+ def log_to_file(self, filename: str) -> None:
208
+ """Log to file and enable debug logging."""
209
+ self.debug = True
210
+ LibraryLogger.configure_logger(logging.DEBUG, file_name=filename)
211
+ logger.debug('Logging to file: %s', filename)
212
+
213
+ def process_devices(self, dev_list_resp: ResponseDeviceListModel) -> bool:
214
+ """Instantiate Device Objects.
215
+
216
+ Internal method run by `get_devices()` to instantiate device objects.
217
+
218
+ """
219
+ current_device_count = len(self._device_container)
220
+
221
+ self._device_container.remove_stale_devices(dev_list_resp)
222
+
223
+ new_device_count = len(self._device_container)
224
+ if new_device_count != current_device_count:
225
+ logger.debug(
226
+ 'Removed %s devices', str(current_device_count - new_device_count)
227
+ )
228
+ current_device_count = new_device_count
229
+ self._device_container.add_new_devices(dev_list_resp, self)
230
+ new_device_count = len(self._device_container)
231
+ if new_device_count != current_device_count:
232
+ logger.debug(
233
+ 'Added %s devices', str(new_device_count - current_device_count)
234
+ )
235
+ return True
236
+
237
+ async def get_devices(self) -> bool:
238
+ """Return tuple listing outlets, switches, and fans of devices.
239
+
240
+ This is also called by `VeSync.update()`
241
+
242
+ Raises:
243
+ VeSyncAPIResponseError: If API response is invalid.
244
+ VeSyncServerError: If server returns an error.
245
+ """
246
+ if not self.enabled:
247
+ return False
248
+
249
+ self.in_process = True
250
+ proc_return = False
251
+ request_model = RequestDeviceListModel(
252
+ token=self.token,
253
+ accountID=self.account_id,
254
+ timeZone=self.time_zone
255
+ )
256
+ response_dict, _ = await self.async_call_api(
257
+ '/cloud/v1/deviceManaged/devices',
258
+ 'post',
259
+ headers=Helpers.req_header_bypass(),
260
+ json_object=request_model.to_dict(),
261
+ )
262
+
263
+ if response_dict is None:
264
+ raise VeSyncAPIResponseError(
265
+ 'Error receiving response to device list request')
266
+
267
+ response = ResponseDeviceListModel.from_dict(response_dict)
268
+
269
+ if response.code == 0:
270
+ proc_return = self.process_devices(response)
271
+ else:
272
+ error_info = ErrorCodes.get_error_info(response.code)
273
+ resp_message = response.msg
274
+ info_msg = f'{error_info.message} ({resp_message})'
275
+ if error_info.error_type == ErrorTypes.SERVER_ERROR:
276
+ raise VeSyncServerError(info_msg)
277
+ raise VeSyncAPIResponseError(
278
+ 'Error receiving response to device list request')
279
+
280
+ self.in_process = False
281
+
282
+ return proc_return
283
+
284
+ async def login(self) -> bool: # pylint: disable=W9006 # pylint mult docstring raises
285
+ """Log into VeSync server.
286
+
287
+ Username and password are provided when class is instantiated.
288
+
289
+ Returns:
290
+ True if login successful, False if not.
291
+
292
+ Raises:
293
+ VeSyncLoginError: If login fails due to invalid username or password.
294
+ VeSyncAPIResponseError: If API response is invalid.
295
+ VeSyncServerError: If server returns an error.
296
+ """
297
+ if not isinstance(self.username, str) or len(self.username) == 0 \
298
+ or not isinstance(self.password, str) or len(self.password) == 0:
299
+ raise VesyncLoginError('Username and password must be specified')
300
+ request_login = RequestLoginModel(
301
+ email=self.username,
302
+ method='login',
303
+ password=self.password,
304
+ )
305
+ resp_dict, _ = await self.async_call_api(
306
+ '/cloud/v1/user/login', 'post',
307
+ json_object=request_login
308
+ )
309
+ if resp_dict is None:
310
+ raise VeSyncAPIResponseError('Error receiving response to login request')
311
+ if resp_dict.get('code') == 0:
312
+ try:
313
+ response_model = ResponseLoginModel.from_dict(resp_dict)
314
+ except Exception as exc:
315
+ logger.debug('Error parsing login response: %s', exc)
316
+ raise VeSyncAPIResponseError(
317
+ 'Error receiving response to login request'
318
+ ) from exc
319
+ result = response_model.result
320
+ self._token = result.token
321
+ self._account_id = result.accountID
322
+ self.country_code = result.countryCode
323
+ self.enabled = True
324
+ logger.debug('Login successful')
325
+ return True
326
+
327
+ error_info = ErrorCodes.get_error_info(resp_dict.get("code"))
328
+ resp_message = resp_dict.get('msg')
329
+ if resp_message is not None:
330
+ error_info.message = f'{error_info.message} ({resp_message})'
331
+ raise VeSyncAPIResponseError('Error receiving response to login request')
332
+
333
+ async def update(self) -> None:
334
+ """Fetch updated information about devices and new device list.
335
+
336
+ Pulls devices list from VeSync and instantiates any new devices. Devices
337
+ are stored in the instance attributes `outlets`, `switches`, `fans`, and
338
+ `bulbs`. The `_device_list` attribute is a dictionary of these attributes.
339
+ """
340
+ if not self.enabled:
341
+ logger.error('Not logged in to VeSync')
342
+ return
343
+ await self.get_devices()
344
+
345
+ await self.update_all_devices()
346
+
347
+ async def update_all_devices(self) -> None:
348
+ """Run `get_details()` for each device and update state."""
349
+ logger.debug('Start updating the device details one by one')
350
+ update_tasks = [device.update() for device in self._device_container]
351
+ for update_coro in asyncio.as_completed(update_tasks):
352
+ try:
353
+ await update_coro
354
+ except VeSyncError as exc:
355
+ logger.debug('Error updating device: %s', exc)
356
+
357
+ async def __aenter__(self) -> Self:
358
+ """Asynchronous context manager enter."""
359
+ return self
360
+
361
+ async def __aexit__(self, *exec_info: object) -> None:
362
+ """Asynchronous context manager exit."""
363
+ if self.session and self._close_session:
364
+ logger.debug("Closing session, exiting context manager")
365
+ await self.session.close()
366
+ return
367
+ logger.debug("Session not closed, exiting context manager")
368
+
369
+ async def async_call_api(
370
+ self,
371
+ api: str,
372
+ method: str,
373
+ json_object: dict | None | DataClassORJSONMixin = None,
374
+ headers: dict | None = None,
375
+ ) -> tuple[dict | None, int | None]:
376
+ """Make API calls by passing endpoint, header and body.
377
+
378
+ api argument is appended to https://smartapi.vesync.com url.
379
+ Raises VeSyncRateLimitError if API returns a rate limit error.
380
+
381
+ Args:
382
+ api (str): Endpoint to call with https://smartapi.vesync.com.
383
+ method (str): HTTP method to use.
384
+ json_object (dict | RequestBaseModel): JSON object to send in body.
385
+ headers (dict): Headers to send with request.
386
+
387
+ Returns:
388
+ tuple[dict | None, int]: Response and status code. Attempts to parse
389
+ response as JSON, if not possible returns None.
390
+
391
+ Raises:
392
+ VeSyncAPIStatusCodeError: If API returns an error status code.
393
+ VeSyncRateLimitError: If API returns a rate limit error.
394
+ VeSyncServerError: If API returns a server error.
395
+ VeSyncTokenError: If API returns an authentication error.
396
+ ClientResponseError: If API returns a client response error.
397
+
398
+ Note:
399
+ Future releases will require the `json_object` argument to be a dataclass,
400
+ instead of dictionary.
401
+ """
402
+ if self.session is None:
403
+ self.session = ClientSession()
404
+ self._close_session = True
405
+ response = None
406
+ status_code = None
407
+ if isinstance(json_object, DataClassORJSONMixin):
408
+ req_dict = json_object.to_dict()
409
+ elif isinstance(json_object, dict):
410
+ req_dict = json_object
411
+ else:
412
+ req_dict = None
413
+ try:
414
+ async with self.session.request(
415
+ method,
416
+ url=API_BASE_URL + api,
417
+ json=req_dict,
418
+ headers=headers,
419
+ raise_for_status=False,
420
+ ) as response:
421
+
422
+ status_code = response.status
423
+ resp_bytes = await response.read()
424
+ if status_code != 200:
425
+ LibraryLogger.log_api_status_error(
426
+ logger,
427
+ request_body=req_dict,
428
+ response=response,
429
+ response_bytes=resp_bytes,
430
+ )
431
+ raise VeSyncAPIStatusCodeError(str(status_code))
432
+
433
+ LibraryLogger.log_api_call(logger, response, resp_bytes, req_dict)
434
+ resp_dict = Helpers.try_json_loads(resp_bytes)
435
+ if isinstance(resp_dict, dict):
436
+ error_info = ErrorCodes.get_error_info(resp_dict.get("code"))
437
+ if resp_dict.get("msg") is not None:
438
+ error_info.message = f"{error_info.message} ({resp_dict['msg']})"
439
+ raise_api_errors(error_info)
440
+
441
+ return resp_dict, status_code
442
+
443
+ except ClientResponseError as e:
444
+ LibraryLogger.log_api_exception(logger, exception=e, request_body=req_dict)
445
+ raise