Moved TuyaCache to __init__.py, and renamed to TuyaDevice. In pytuya, renamed TuyaDevice to TuyaInterface

This commit is contained in:
rospogrigio
2020-09-22 00:49:05 +02:00
committed by rospogrigio
parent dd48fc00f5
commit 83b3b6f21b
8 changed files with 113 additions and 366 deletions

View File

@@ -2,6 +2,8 @@
import asyncio import asyncio
import logging import logging
import voluptuous as vol import voluptuous as vol
from time import time, sleep
from threading import Lock
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
@@ -21,6 +23,10 @@ from homeassistant.helpers.entity import Entity
from . import pytuya from . import pytuya
from .const import CONF_LOCAL_KEY, CONF_PROTOCOL_VERSION, DOMAIN from .const import CONF_LOCAL_KEY, CONF_PROTOCOL_VERSION, DOMAIN
import pprint
pp = pprint.PrettyPrinter(indent=4)
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
DEFAULT_ID = "1" DEFAULT_ID = "1"
@@ -52,18 +58,18 @@ def prepare_setup_entities(config_entry, platform):
if not entities_to_setup: if not entities_to_setup:
return None, None return None, None
device = pytuya.TuyaDevice( tuyainterface = pytuya.TuyaInterface(
config_entry.data[CONF_DEVICE_ID], config_entry.data[CONF_DEVICE_ID],
config_entry.data[CONF_HOST], config_entry.data[CONF_HOST],
config_entry.data[CONF_LOCAL_KEY], config_entry.data[CONF_LOCAL_KEY],
float(config_entry.data[CONF_PROTOCOL_VERSION]),
) )
device.set_version(float(config_entry.data[CONF_PROTOCOL_VERSION]))
for device_config in entities_to_setup: for interface_config in entities_to_setup:
# this has to be done in case the device type is type_0d # this has to be done in case the device type is type_0d
device.add_dps_to_request(device_config[CONF_ID]) tuyainterface.add_dps_to_request(interface_config[CONF_ID])
return device, entities_to_setup return tuyainterface, entities_to_setup
def import_from_yaml(hass, config, platform): def import_from_yaml(hass, config, platform):
@@ -132,6 +138,80 @@ def get_entity_config(config_entry, dps_id):
raise Exception(f"missing entity config for id {dps_id}") raise Exception(f"missing entity config for id {dps_id}")
class TuyaDevice:
"""Cache wrapper for pytuya.TuyaInterface"""
def __init__(self, interface, friendly_name):
"""Initialize the cache."""
self._cached_status = ""
self._cached_status_time = 0
self._interface = interface
self._friendly_name = friendly_name
self._lock = Lock()
@property
def unique_id(self):
"""Return unique device identifier."""
return self._interface.id
def __get_status(self):
_LOGGER.debug("running def __get_status from TuyaDevice")
for i in range(5):
try:
status = self._interface.status()
# print("STATUS OF [{}] IS [{}]".format(self._interface.address,status))
return status
except Exception:
print(
"Failed to update status of device [{}]".format(
self._interface.address
)
)
sleep(1.0)
if i + 1 == 3:
_LOGGER.error(
"Failed to update status of device %s", self._interface.address
)
# return None
raise ConnectionError("Failed to update status .")
def set_dps(self, state, dps_index):
#_LOGGER.info("running def set_dps from cover")
"""Change the Tuya switch status and clear the cache."""
self._cached_status = ""
self._cached_status_time = 0
for i in range(5):
try:
#_LOGGER.info("Running a try from def set_dps from cover where state=%s and dps_index=%s", state, dps_index)
return self._interface.set_dps(state, dps_index)
except Exception:
print(
"Failed to set status of device [{}]".format(self._interface.address)
)
if i + 1 == 3:
_LOGGER.error(
"Failed to set status of device %s", self._interface.address
)
return
# raise ConnectionError("Failed to set status.")
def status(self):
"""Get state of Tuya switch and cache the results."""
_LOGGER.debug("running def status(self) from TuyaDevice")
self._lock.acquire()
try:
now = time()
if not self._cached_status or now - self._cached_status_time > 15:
sleep(0.5)
self._cached_status = self.__get_status()
self._cached_status_time = time()
return self._cached_status
finally:
self._lock.release()
class LocalTuyaEntity(Entity): class LocalTuyaEntity(Entity):
"""Representation of a Tuya entity.""" """Representation of a Tuya entity."""
@@ -174,7 +254,7 @@ class LocalTuyaEntity(Entity):
def dps(self, dps_index): def dps(self, dps_index):
"""Return cached value for DPS index.""" """Return cached value for DPS index."""
value = self._status["dps"].get(dps_index) value = self._status["dps"].get(str(dps_index))
if value is None: if value is None:
_LOGGER.warning( _LOGGER.warning(
"Entity %s is requesting unknown DPS index %s", "Entity %s is requesting unknown DPS index %s",

View File

@@ -128,17 +128,17 @@ def strip_dps_values(user_input, dps_strings):
async def validate_input(hass: core.HomeAssistant, data): async def validate_input(hass: core.HomeAssistant, data):
"""Validate the user input allows us to connect.""" """Validate the user input allows us to connect."""
pytuyadevice = pytuya.TuyaDevice( tuyainterface = pytuya.TuyaInterface(
data[CONF_DEVICE_ID], data[CONF_DEVICE_ID],
data[CONF_HOST], data[CONF_HOST],
data[CONF_LOCAL_KEY], data[CONF_LOCAL_KEY],
float(data[CONF_PROTOCOL_VERSION]),
) )
pytuyadevice.set_version(float(data[CONF_PROTOCOL_VERSION]))
detected_dps = {} detected_dps = {}
try: try:
detected_dps = await hass.async_add_executor_job( detected_dps = await hass.async_add_executor_job(
pytuyadevice.detect_available_dps tuyainterface.detect_available_dps
) )
except (ConnectionRefusedError, ConnectionResetError): except (ConnectionRefusedError, ConnectionResetError):
raise CannotConnect raise CannotConnect

View File

@@ -20,7 +20,6 @@ cover:
""" """
import logging import logging
from time import time, sleep from time import time, sleep
from threading import Lock
import voluptuous as vol import voluptuous as vol
@@ -41,6 +40,7 @@ import homeassistant.helpers.config_validation as cv
from . import ( from . import (
BASE_PLATFORM_SCHEMA, BASE_PLATFORM_SCHEMA,
TuyaDevice,
LocalTuyaEntity, LocalTuyaEntity,
prepare_setup_entities, prepare_setup_entities,
import_from_yaml, import_from_yaml,
@@ -79,7 +79,7 @@ def flow_schema(dps):
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
"""Setup a Tuya cover based on a config entry.""" """Setup a Tuya cover based on a config entry."""
device, entities_to_setup = prepare_setup_entities( tuyainterface, entities_to_setup = prepare_setup_entities(
config_entry, DOMAIN config_entry, DOMAIN
) )
if not entities_to_setup: if not entities_to_setup:
@@ -89,7 +89,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
for device_config in entities_to_setup: for device_config in entities_to_setup:
covers.append( covers.append(
LocaltuyaCover( LocaltuyaCover(
TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), TuyaDevice(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]),
config_entry, config_entry,
device_config[CONF_ID], device_config[CONF_ID],
) )
@@ -102,77 +102,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
return import_from_yaml(hass, config, DOMAIN) return import_from_yaml(hass, config, DOMAIN)
class TuyaCache:
"""Cache wrapper for pytuya.TuyaDevice"""
def __init__(self, device, friendly_name):
"""Initialize the cache."""
self._cached_status = ""
self._cached_status_time = 0
self._device = device
self._friendly_name = friendly_name
self._lock = Lock()
@property
def unique_id(self):
"""Return unique device identifier."""
return self._device.id
def __get_status(self):
# _LOGGER.info("running def __get_status from cover")
for i in range(5):
try:
status = self._device.status()
return status
except Exception:
print(
"Failed to update status of device [{}]".format(
self._device.address
)
)
sleep(1.0)
if i + 1 == 3:
_LOGGER.error(
"Failed to update status of device %s", self._device.address
)
# return None
raise ConnectionError("Failed to update status .")
def set_dps(self, state, dps_index):
#_LOGGER.info("running def set_dps from cover")
"""Change the Tuya switch status and clear the cache."""
self._cached_status = ""
self._cached_status_time = 0
for i in range(5):
try:
#_LOGGER.info("Running a try from def set_dps from cover where state=%s and dps_index=%s", state, dps_index)
return self._device.set_dps(state, dps_index)
except Exception:
print(
"Failed to set status of device [{}]".format(self._device.address)
)
if i + 1 == 3:
_LOGGER.error(
"Failed to set status of device %s", self._device.address
)
return
# raise ConnectionError("Failed to set status.")
def status(self):
"""Get state of Tuya switch and cache the results."""
# _LOGGER.info("running def status(self) from cover")
self._lock.acquire()
try:
now = time()
if not self._cached_status or now - self._cached_status_time > 15:
sleep(0.5)
self._cached_status = self.__get_status()
self._cached_status_time = time()
return self._cached_status
finally:
self._lock.release()
class LocaltuyaCover(LocalTuyaEntity, CoverEntity): class LocaltuyaCover(LocalTuyaEntity, CoverEntity):
"""Tuya cover devices.""" """Tuya cover devices."""

View File

@@ -16,7 +16,6 @@ fan:
""" """
import logging import logging
from time import time, sleep from time import time, sleep
from threading import Lock
from homeassistant.components.fan import ( from homeassistant.components.fan import (
FanEntity, FanEntity,
@@ -33,6 +32,7 @@ from homeassistant.const import CONF_ID, CONF_FRIENDLY_NAME
from . import ( from . import (
BASE_PLATFORM_SCHEMA, BASE_PLATFORM_SCHEMA,
TuyaDevice,
LocalTuyaEntity, LocalTuyaEntity,
prepare_setup_entities, prepare_setup_entities,
import_from_yaml, import_from_yaml,
@@ -50,7 +50,7 @@ def flow_schema(dps):
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
"""Setup a Tuya fan based on a config entry.""" """Setup a Tuya fan based on a config entry."""
device, entities_to_setup = prepare_setup_entities(config_entry, DOMAIN) tuyainterface, entities_to_setup = prepare_setup_entities(config_entry, DOMAIN)
if not entities_to_setup: if not entities_to_setup:
return return
@@ -59,7 +59,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
for device_config in entities_to_setup: for device_config in entities_to_setup:
fans.append( fans.append(
LocaltuyaFan( LocaltuyaFan(
TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), TuyaCache(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]),
config_entry, config_entry,
device_config[CONF_ID], device_config[CONF_ID],
) )
@@ -73,75 +73,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
return import_from_yaml(hass, config, DOMAIN) return import_from_yaml(hass, config, DOMAIN)
# TODO: Needed only to be compatible with LocalTuyaEntity
class TuyaCache:
"""Cache wrapper for pytuya.TuyaDevice"""
def __init__(self, device, friendly_name):
"""Initialize the cache."""
self._cached_status = ""
self._cached_status_time = 0
self._device = device
self._friendly_name = friendly_name
self._lock = Lock()
@property
def unique_id(self):
"""Return unique device identifier."""
return self._device.id
def __get_status(self):
for i in range(5):
try:
status = self._device.status()
return status
except Exception:
print(
"Failed to update status of device [{}]".format(
self._device.address
)
)
sleep(1.0)
if i + 1 == 3:
_LOGGER.error(
"Failed to update status of device %s", self._device.address
)
# return None
raise ConnectionError("Failed to update status .")
def set_dps(self, state, dps_index):
"""Change the Tuya switch status and clear the cache."""
self._cached_status = ""
self._cached_status_time = 0
for i in range(5):
try:
return self._device.set_dps(state, dps_index)
except Exception:
print(
"Failed to set status of device [{}]".format(self._device.address)
)
if i + 1 == 3:
_LOGGER.error(
"Failed to set status of device %s", self._device.address
)
return
# raise ConnectionError("Failed to set status.")
self.update()
def status(self):
"""Get state of Tuya switch and cache the results."""
self._lock.acquire()
try:
now = time()
if not self._cached_status or now - self._cached_status_time > 15:
sleep(0.5)
self._cached_status = self.__get_status()
self._cached_status_time = time()
return self._cached_status
finally:
self._lock.release()
class LocaltuyaFan(LocalTuyaEntity, FanEntity): class LocaltuyaFan(LocalTuyaEntity, FanEntity):
"""Representation of a Tuya fan.""" """Representation of a Tuya fan."""

View File

@@ -14,7 +14,6 @@ light:
import socket import socket
import logging import logging
from time import time, sleep from time import time, sleep
from threading import Lock
from homeassistant.const import ( from homeassistant.const import (
CONF_ID, CONF_ID,
@@ -33,6 +32,7 @@ from homeassistant.components.light import (
from . import ( from . import (
BASE_PLATFORM_SCHEMA, BASE_PLATFORM_SCHEMA,
TuyaDevice,
LocalTuyaEntity, LocalTuyaEntity,
import_from_yaml, import_from_yaml,
prepare_setup_entities, prepare_setup_entities,
@@ -60,18 +60,18 @@ def flow_schema(dps):
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
"""Setup a Tuya light based on a config entry.""" """Setup a Tuya light based on a config entry."""
device, entities_to_setup = prepare_setup_entities(config_entry, DOMAIN) tuyainterface, entities_to_setup = prepare_setup_entities(config_entry, DOMAIN)
if not entities_to_setup: if not entities_to_setup:
return return
lights = [] lights = []
for device_config in entities_to_setup: for device_config in entities_to_setup:
# this has to be done in case the device type is type_0d # this has to be done in case the device type is type_0d
device.add_dps_to_request(device_config[CONF_ID]) tuyainterface.add_dps_to_request(device_config[CONF_ID])
lights.append( lights.append(
LocaltuyaLight( LocaltuyaLight(
TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), TuyaCache(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]),
config_entry, config_entry,
device_config[CONF_ID], device_config[CONF_ID],
) )
@@ -85,64 +85,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
return import_from_yaml(hass, config, DOMAIN) return import_from_yaml(hass, config, DOMAIN)
class TuyaCache:
"""Cache wrapper for pytuya.TuyaDevices"""
def __init__(self, device, friendly_name):
"""Initialize the cache."""
self._cached_status = ""
self._cached_status_time = 0
self._device = device
self._friendly_name = friendly_name
self._lock = Lock()
@property
def unique_id(self):
"""Return unique device identifier."""
return self._device.id
def __get_status(self):
for i in range(5):
try:
status = self._device.status()
return status
except Exception:
print(
"Failed to update status of device [{}]".format(
self._device.address
)
)
sleep(1.0)
if i + 1 == 3:
_LOGGER.error(
"Failed to update status of device %s", self._device.address
)
# return None
raise ConnectionError("Failed to update status .")
def set_dps(self, state, dps_index):
"""Change the Tuya light status and clear the cache."""
self._cached_status = ""
self._cached_status_time = 0
for _ in range(UPDATE_RETRY_LIMIT):
try:
return self._device.set_dps(state, dps_index)
except ConnectionError:
pass
except socket.timeout:
pass
_LOGGER.warning("Failed to set status after %d tries", UPDATE_RETRY_LIMIT)
def status(self):
"""Get state of Tuya light and cache the results."""
with self._lock:
now = time()
if not self._cached_status or now - self._cached_status_time > 15:
sleep(0.5)
self._cached_status = self.__get_status()
self._cached_status_time = time()
return self._cached_status
class LocaltuyaLight(LocalTuyaEntity, LightEntity): class LocaltuyaLight(LocalTuyaEntity, LightEntity):
"""Representation of a Tuya light.""" """Representation of a Tuya light."""

View File

@@ -11,7 +11,7 @@
For more information see https://github.com/clach04/python-tuya For more information see https://github.com/clach04/python-tuya
Classes Classes
TuyaDevice(dev_id, address, local_key=None) TuyaInterface(dev_id, address, local_key=None)
dev_id (str): Device ID e.g. 01234567891234567890 dev_id (str): Device ID e.g. 01234567891234567890
address (str): Device Network IP Address e.g. 10.0.1.99 address (str): Device Network IP Address e.g. 10.0.1.99
local_key (str, optional): The encryption key. Defaults to None. local_key (str, optional): The encryption key. Defaults to None.
@@ -174,8 +174,8 @@ payload_dict = {
} }
class TuyaDevice(object): class TuyaInterface(object):
def __init__(self, dev_id, address, local_key, connection_timeout=10): def __init__(self, dev_id, address, local_key, protocol_version, connection_timeout=10):
""" """
Represents a Tuya device. Represents a Tuya device.
@@ -192,7 +192,7 @@ class TuyaDevice(object):
self.address = address self.address = address
self.local_key = local_key.encode('latin1') self.local_key = local_key.encode('latin1')
self.connection_timeout = connection_timeout self.connection_timeout = connection_timeout
self.version = 3.1 self.version = protocol_version
self.dev_type = 'type_0a' self.dev_type = 'type_0a'
self.dps_to_request = {} self.dps_to_request = {}
@@ -239,9 +239,6 @@ class TuyaDevice(object):
s.close() s.close()
return data return data
def set_version(self, version):
self.version = version
def detect_available_dps(self): def detect_available_dps(self):
# type_0d devices need a sort of bruteforce querying in order to detect the list of available dps # type_0d devices need a sort of bruteforce querying in order to detect the list of available dps
# experience shows that the dps available are usually in the ranges [1-25] and [100-110] # experience shows that the dps available are usually in the ranges [1-25] and [100-110]
@@ -395,6 +392,7 @@ class TuyaDevice(object):
result = result[16:] # remove (what I'm guessing, but not confirmed is) 16-bytes of MD5 hexdigest of payload result = result[16:] # remove (what I'm guessing, but not confirmed is) 16-bytes of MD5 hexdigest of payload
cipher = AESCipher(self.local_key) cipher = AESCipher(self.local_key)
result = cipher.decrypt(result) result = cipher.decrypt(result)
print('decrypted result=[{}]'.format(result))
log.debug('decrypted result=%r', result) log.debug('decrypted result=%r', result)
if not isinstance(result, str): if not isinstance(result, str):
result = result.decode() result = result.decode()

View File

@@ -16,7 +16,6 @@ sensor:
""" """
import logging import logging
from time import time, sleep from time import time, sleep
from threading import Lock
import voluptuous as vol import voluptuous as vol
@@ -31,6 +30,7 @@ from homeassistant.const import (
from . import ( from . import (
BASE_PLATFORM_SCHEMA, BASE_PLATFORM_SCHEMA,
TuyaDevice,
LocalTuyaEntity, LocalTuyaEntity,
prepare_setup_entities, prepare_setup_entities,
import_from_yaml, import_from_yaml,
@@ -57,7 +57,7 @@ def flow_schema(dps):
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
"""Setup a Tuya sensor based on a config entry.""" """Setup a Tuya sensor based on a config entry."""
device, entities_to_setup = prepare_setup_entities(config_entry, DOMAIN) tuyainterface, entities_to_setup = prepare_setup_entities(config_entry, DOMAIN)
if not entities_to_setup: if not entities_to_setup:
return return
@@ -65,7 +65,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
for device_config in entities_to_setup: for device_config in entities_to_setup:
sensors.append( sensors.append(
LocaltuyaSensor( LocaltuyaSensor(
TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), TuyaCache(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]),
config_entry, config_entry,
device_config[CONF_ID], device_config[CONF_ID],
) )
@@ -79,74 +79,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
return import_from_yaml(hass, config, DOMAIN) return import_from_yaml(hass, config, DOMAIN)
class TuyaCache:
"""Cache wrapper for pytuya.TuyaDevice"""
def __init__(self, device, friendly_name):
"""Initialize the cache."""
self._cached_status = ""
self._cached_status_time = 0
self._device = device
self._friendly_name = friendly_name
self._lock = Lock()
@property
def unique_id(self):
"""Return unique device identifier."""
return self._device.id
def __get_status(self):
for i in range(5):
try:
status = self._device.status()
return status
except Exception:
print(
"Failed to update status of device [{}]".format(
self._device.address
)
)
sleep(1.0)
if i + 1 == 3:
_LOGGER.error(
"Failed to update status of device %s", self._device.address
)
# return None
raise ConnectionError("Failed to update status .")
def set_dps(self, state, dps_index):
"""Change the Tuya sensor status and clear the cache."""
self._cached_status = ""
self._cached_status_time = 0
for i in range(5):
try:
return self._device.set_dps(state, dps_index)
except Exception:
print(
"Failed to set status of device [{}]".format(self._device.address)
)
if i + 1 == 3:
_LOGGER.error(
"Failed to set status of device %s", self._device.address
)
return
# raise ConnectionError("Failed to set status.")
self.update()
def status(self):
"""Get state of Tuya sensor and cache the results."""
self._lock.acquire()
try:
now = time()
if not self._cached_status or now - self._cached_status_time > 15:
sleep(0.5)
self._cached_status = self.__get_status()
self._cached_status_time = time()
return self._cached_status
finally:
self._lock.release()
class LocaltuyaSensor(LocalTuyaEntity): class LocaltuyaSensor(LocalTuyaEntity):
"""Representation of a Tuya sensor.""" """Representation of a Tuya sensor."""

View File

@@ -26,7 +26,6 @@ switch:
""" """
import logging import logging
from time import time, sleep from time import time, sleep
from threading import Lock
import voluptuous as vol import voluptuous as vol
@@ -45,6 +44,7 @@ import homeassistant.helpers.config_validation as cv
from . import ( from . import (
BASE_PLATFORM_SCHEMA, BASE_PLATFORM_SCHEMA,
TuyaDevice,
LocalTuyaEntity, LocalTuyaEntity,
prepare_setup_entities, prepare_setup_entities,
import_from_yaml, import_from_yaml,
@@ -95,22 +95,22 @@ def flow_schema(dps):
async def async_setup_entry(hass, config_entry, async_add_entities): async def async_setup_entry(hass, config_entry, async_add_entities):
"""Setup a Tuya switch based on a config entry.""" """Setup a Tuya switch based on a config entry."""
device, entities_to_setup = prepare_setup_entities(config_entry, DOMAIN) tuyainterface, entities_to_setup = prepare_setup_entities(config_entry, DOMAIN)
if not entities_to_setup: if not entities_to_setup:
return return
switches = [] switches = []
for device_config in entities_to_setup: for device_config in entities_to_setup:
if device_config.get(CONF_CURRENT, "-1") != "-1": if device_config.get(CONF_CURRENT, "-1") != "-1":
device.add_dps_to_request(device_config.get(CONF_CURRENT)) tuyainterface.add_dps_to_request(device_config.get(CONF_CURRENT))
if device_config.get(CONF_CURRENT_CONSUMPTION, "-1") != "-1": if device_config.get(CONF_CURRENT_CONSUMPTION, "-1") != "-1":
device.add_dps_to_request(device_config.get(CONF_CURRENT_CONSUMPTION)) tuyainterface.add_dps_to_request(device_config.get(CONF_CURRENT_CONSUMPTION))
if device_config.get(CONF_VOLTAGE, "-1") != "-1": if device_config.get(CONF_VOLTAGE, "-1") != "-1":
device.add_dps_to_request(device_config.get(CONF_VOLTAGE)) tuyainterface.add_dps_to_request(device_config.get(CONF_VOLTAGE))
switches.append( switches.append(
LocaltuyaSwitch( LocaltuyaSwitch(
TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), TuyaDevice(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]),
config_entry, config_entry,
device_config[CONF_ID], device_config[CONF_ID],
) )
@@ -124,71 +124,6 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
return import_from_yaml(hass, config, DOMAIN) return import_from_yaml(hass, config, DOMAIN)
class TuyaCache:
def __init__(self, device, friendly_name):
"""Initialize the cache."""
self._cached_status = ""
self._cached_status_time = 0
self._device = device
self._friendly_name = friendly_name
self._lock = Lock()
@property
def unique_id(self):
"""Return unique device identifier."""
return self._device.id
def __get_status(self):
for i in range(5):
try:
status = self._device.status()
return status
except Exception:
print(
"Failed to update status of device [{}]".format(
self._device.address
)
)
sleep(1.0)
if i + 1 == 3:
_LOGGER.error(
"Failed to update status of device %s", self._device.address
)
# return None
raise ConnectionError("Failed to update status .")
def set_dps(self, state, dps_index):
"""Change the Tuya switch status and clear the cache."""
self._cached_status = ""
self._cached_status_time = 0
for i in range(5):
try:
return self._device.set_dps(state, dps_index)
except Exception:
print(
"Failed to set status of device [{}]".format(self._device.address)
)
if i + 1 == 3:
_LOGGER.error(
"Failed to set status of device %s", self._device.address
)
return
# raise ConnectionError("Failed to set status.")
self.update()
def status(self):
"""Get state of Tuya switch and cache the results."""
self._lock.acquire()
try:
now = time()
if not self._cached_status or now - self._cached_status_time > 15:
sleep(0.5)
self._cached_status = self.__get_status()
self._cached_status_time = time()
return self._cached_status
finally:
self._lock.release()
class LocaltuyaSwitch(LocalTuyaEntity, SwitchEntity): class LocaltuyaSwitch(LocalTuyaEntity, SwitchEntity):