diff --git a/custom_components/localtuya/__init__.py b/custom_components/localtuya/__init__.py index 64d7e57..67f0b9d 100644 --- a/custom_components/localtuya/__init__.py +++ b/custom_components/localtuya/__init__.py @@ -2,6 +2,8 @@ import asyncio import logging import voluptuous as vol +from time import time, sleep +from threading import Lock from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry from homeassistant.core import HomeAssistant @@ -21,6 +23,10 @@ from homeassistant.helpers.entity import Entity from . import pytuya from .const import CONF_LOCAL_KEY, CONF_PROTOCOL_VERSION, DOMAIN + +import pprint +pp = pprint.PrettyPrinter(indent=4) + _LOGGER = logging.getLogger(__name__) DEFAULT_ID = "1" @@ -52,18 +58,18 @@ def prepare_setup_entities(config_entry, platform): if not entities_to_setup: return None, None - device = pytuya.TuyaDevice( + tuyainterface = pytuya.TuyaInterface( config_entry.data[CONF_DEVICE_ID], config_entry.data[CONF_HOST], 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 - 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): @@ -132,6 +138,80 @@ def get_entity_config(config_entry, 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): """Representation of a Tuya entity.""" @@ -174,7 +254,7 @@ class LocalTuyaEntity(Entity): def dps(self, 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: _LOGGER.warning( "Entity %s is requesting unknown DPS index %s", diff --git a/custom_components/localtuya/config_flow.py b/custom_components/localtuya/config_flow.py index 6368ed4..070f1c7 100644 --- a/custom_components/localtuya/config_flow.py +++ b/custom_components/localtuya/config_flow.py @@ -128,17 +128,17 @@ def strip_dps_values(user_input, dps_strings): async def validate_input(hass: core.HomeAssistant, data): """Validate the user input allows us to connect.""" - pytuyadevice = pytuya.TuyaDevice( + tuyainterface = pytuya.TuyaInterface( data[CONF_DEVICE_ID], data[CONF_HOST], data[CONF_LOCAL_KEY], + float(data[CONF_PROTOCOL_VERSION]), ) - pytuyadevice.set_version(float(data[CONF_PROTOCOL_VERSION])) detected_dps = {} try: detected_dps = await hass.async_add_executor_job( - pytuyadevice.detect_available_dps + tuyainterface.detect_available_dps ) except (ConnectionRefusedError, ConnectionResetError): raise CannotConnect diff --git a/custom_components/localtuya/cover.py b/custom_components/localtuya/cover.py index b33e1f4..49b3c88 100644 --- a/custom_components/localtuya/cover.py +++ b/custom_components/localtuya/cover.py @@ -20,7 +20,6 @@ cover: """ import logging from time import time, sleep -from threading import Lock import voluptuous as vol @@ -41,6 +40,7 @@ import homeassistant.helpers.config_validation as cv from . import ( BASE_PLATFORM_SCHEMA, + TuyaDevice, LocalTuyaEntity, prepare_setup_entities, import_from_yaml, @@ -79,7 +79,7 @@ def flow_schema(dps): async def async_setup_entry(hass, config_entry, async_add_entities): """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 ) 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: covers.append( LocaltuyaCover( - TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), + TuyaDevice(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]), config_entry, 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) -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): """Tuya cover devices.""" diff --git a/custom_components/localtuya/fan.py b/custom_components/localtuya/fan.py index af19d47..80cb0df 100644 --- a/custom_components/localtuya/fan.py +++ b/custom_components/localtuya/fan.py @@ -16,7 +16,6 @@ fan: """ import logging from time import time, sleep -from threading import Lock from homeassistant.components.fan import ( FanEntity, @@ -33,6 +32,7 @@ from homeassistant.const import CONF_ID, CONF_FRIENDLY_NAME from . import ( BASE_PLATFORM_SCHEMA, + TuyaDevice, LocalTuyaEntity, prepare_setup_entities, import_from_yaml, @@ -50,7 +50,7 @@ def flow_schema(dps): async def async_setup_entry(hass, config_entry, async_add_entities): """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: return @@ -59,7 +59,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities): for device_config in entities_to_setup: fans.append( LocaltuyaFan( - TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), + TuyaCache(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]), config_entry, 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) -# 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): """Representation of a Tuya fan.""" diff --git a/custom_components/localtuya/light.py b/custom_components/localtuya/light.py index ec45cda..8923fa1 100644 --- a/custom_components/localtuya/light.py +++ b/custom_components/localtuya/light.py @@ -14,7 +14,6 @@ light: import socket import logging from time import time, sleep -from threading import Lock from homeassistant.const import ( CONF_ID, @@ -33,6 +32,7 @@ from homeassistant.components.light import ( from . import ( BASE_PLATFORM_SCHEMA, + TuyaDevice, LocalTuyaEntity, import_from_yaml, prepare_setup_entities, @@ -60,18 +60,18 @@ def flow_schema(dps): async def async_setup_entry(hass, config_entry, async_add_entities): """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: return lights = [] for device_config in entities_to_setup: # 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( LocaltuyaLight( - TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), + TuyaCache(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]), config_entry, 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) -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): """Representation of a Tuya light.""" diff --git a/custom_components/localtuya/pytuya/__init__.py b/custom_components/localtuya/pytuya/__init__.py index ad86b6f..0746337 100644 --- a/custom_components/localtuya/pytuya/__init__.py +++ b/custom_components/localtuya/pytuya/__init__.py @@ -11,7 +11,7 @@ For more information see https://github.com/clach04/python-tuya Classes - TuyaDevice(dev_id, address, local_key=None) + TuyaInterface(dev_id, address, local_key=None) dev_id (str): Device ID e.g. 01234567891234567890 address (str): Device Network IP Address e.g. 10.0.1.99 local_key (str, optional): The encryption key. Defaults to None. @@ -174,8 +174,8 @@ payload_dict = { } -class TuyaDevice(object): - def __init__(self, dev_id, address, local_key, connection_timeout=10): +class TuyaInterface(object): + def __init__(self, dev_id, address, local_key, protocol_version, connection_timeout=10): """ Represents a Tuya device. @@ -192,7 +192,7 @@ class TuyaDevice(object): self.address = address self.local_key = local_key.encode('latin1') self.connection_timeout = connection_timeout - self.version = 3.1 + self.version = protocol_version self.dev_type = 'type_0a' self.dps_to_request = {} @@ -239,9 +239,6 @@ class TuyaDevice(object): s.close() return data - def set_version(self, version): - self.version = version - def detect_available_dps(self): # 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] @@ -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 cipher = AESCipher(self.local_key) result = cipher.decrypt(result) + print('decrypted result=[{}]'.format(result)) log.debug('decrypted result=%r', result) if not isinstance(result, str): result = result.decode() diff --git a/custom_components/localtuya/sensor.py b/custom_components/localtuya/sensor.py index 80022d4..473cd72 100644 --- a/custom_components/localtuya/sensor.py +++ b/custom_components/localtuya/sensor.py @@ -16,7 +16,6 @@ sensor: """ import logging from time import time, sleep -from threading import Lock import voluptuous as vol @@ -31,6 +30,7 @@ from homeassistant.const import ( from . import ( BASE_PLATFORM_SCHEMA, + TuyaDevice, LocalTuyaEntity, prepare_setup_entities, import_from_yaml, @@ -57,7 +57,7 @@ def flow_schema(dps): async def async_setup_entry(hass, config_entry, async_add_entities): """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: return @@ -65,7 +65,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities): for device_config in entities_to_setup: sensors.append( LocaltuyaSensor( - TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), + TuyaCache(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]), config_entry, 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) -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): """Representation of a Tuya sensor.""" diff --git a/custom_components/localtuya/switch.py b/custom_components/localtuya/switch.py index 52c1c10..faa6270 100644 --- a/custom_components/localtuya/switch.py +++ b/custom_components/localtuya/switch.py @@ -26,7 +26,6 @@ switch: """ import logging from time import time, sleep -from threading import Lock import voluptuous as vol @@ -45,6 +44,7 @@ import homeassistant.helpers.config_validation as cv from . import ( BASE_PLATFORM_SCHEMA, + TuyaDevice, LocalTuyaEntity, prepare_setup_entities, import_from_yaml, @@ -95,22 +95,22 @@ def flow_schema(dps): async def async_setup_entry(hass, config_entry, async_add_entities): """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: return switches = [] for device_config in entities_to_setup: 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": - 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": - device.add_dps_to_request(device_config.get(CONF_VOLTAGE)) + tuyainterface.add_dps_to_request(device_config.get(CONF_VOLTAGE)) switches.append( LocaltuyaSwitch( - TuyaCache(device, config_entry.data[CONF_FRIENDLY_NAME]), + TuyaDevice(tuyainterface, config_entry.data[CONF_FRIENDLY_NAME]), config_entry, 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) -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):