-
Notifications
You must be signed in to change notification settings - Fork 1
/
tuya.py
71 lines (60 loc) · 1.91 KB
/
tuya.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
"""
A sink to control Tuya/Smart Life devices.
"""
import logging
from functools import lru_cache
from tuyapy import TuyaApi
from typing_extensions import Literal
from senor_octopus.types import Stream
_logger = logging.getLogger(__name__)
@lru_cache(maxsize=None)
def authenticate(email: str, password: str, country: str, application: str) -> TuyaApi:
"""
Cached authentication to Tuya/Smart Life.
"""
_logger.debug("Authenticating")
api = TuyaApi()
api.init(email, password, country, application)
return api
async def tuya( # pylint: disable=too-many-arguments
stream: Stream,
device: str,
email: str,
password: str,
country: str = "1",
application: str = Literal["smart_life", "tuya"],
) -> None:
"""
Send commands to a Tuya/Smart Life device.
Currently this plugin supports sending on and off events, but
it can be easily modified to support changing the color of a
lightbulb.
Parameters
----------
stream
The incoming stream of events
device
The name of the device to be controlled
email
The email of the account
password
The password of the account
country
Country telephone code
application
The application code, either "tuya" or "smart_life"
"""
api = authenticate(email, password, country, application)
devices = {d.name(): d for d in api.get_all_devices()}
if device not in devices:
valid = ", ".join(f'"{name}"' for name in devices)
_logger.error('Device "%s" not found. Available devices: %s', device, valid)
return
async for event in stream: # pragma: no cover
_logger.debug(event)
if event["value"].lower() == "on":
devices[device].turn_on()
elif event["value"].lower() == "off":
devices[device].turn_off()
else:
_logger.warning("Unknown value: %s", event["value"])