Pytuya library refactoring and code cleaning

This commit is contained in:
rospogrigio
2020-09-11 11:46:01 +02:00
parent 2fd6c18271
commit 184199ef87
5 changed files with 66 additions and 349 deletions

View File

@@ -35,7 +35,7 @@ from threading import Lock
_LOGGER = logging.getLogger(__name__)
REQUIREMENTS = ['pytuya==7.0.9']
REQUIREMENTS = ['pytuya>=8.0.0']
CONF_DEVICE_ID = 'device_id'
CONF_LOCAL_KEY = 'local_key'
@@ -84,7 +84,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
devices = config.get(CONF_SWITCHES)
switches = []
pytuyadevice = pytuya.OutletDevice(config.get(CONF_DEVICE_ID), config.get(CONF_HOST), config.get(CONF_LOCAL_KEY))
pytuyadevice = pytuya.PytuyaDevice(config.get(CONF_DEVICE_ID), config.get(CONF_HOST), config.get(CONF_LOCAL_KEY))
pytuyadevice.set_version(float(config.get(CONF_PROTOCOL_VERSION)))
if len(devices) > 0:
@@ -101,7 +101,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
outlet_device = TuyaCache(pytuyadevice)
switches.append(
TuyaDevice(
LocaltuyaSwitch(
outlet_device,
device_config.get(CONF_NAME),
device_config.get(CONF_FRIENDLY_NAME, object_id),
@@ -127,7 +127,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
pytuyadevice.set_dpsUsed(dps)
outlet_device = TuyaCache(pytuyadevice)
switches.append(
TuyaDevice(
LocaltuyaSwitch(
outlet_device,
config.get(CONF_NAME),
config.get(CONF_FRIENDLY_NAME),
@@ -145,7 +145,7 @@ def setup_platform(hass, config, add_devices, discovery_info=None):
add_devices(switches, True)
class TuyaCache:
"""Cache wrapper for pytuya.OutletDevice"""
"""Cache wrapper for pytuya.PytuyaDevice"""
def __init__(self, device):
"""Initialize the cache."""
@@ -172,13 +172,13 @@ class TuyaCache:
# return None
raise ConnectionError("Failed to update status .")
def set_status(self, state, switchid):
def set_dps(self, state, switchid):
"""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_status(state, switchid)
return self._device.set_dps(state, switchid)
except Exception:
print('Failed to set status of device [{}]'.format(self._device.address))
if i+1 == 3:
@@ -199,7 +199,7 @@ class TuyaCache:
finally:
self._lock.release()
class TuyaDevice(SwitchEntity):
class LocaltuyaSwitch(SwitchEntity):
"""Representation of a Tuya switch."""
def __init__(self, device, name, friendly_name, icon, switchid, attr_current, attr_consumption, attr_voltage):
@@ -258,11 +258,11 @@ class TuyaDevice(SwitchEntity):
def turn_on(self, **kwargs):
"""Turn Tuya switch on."""
self._device.set_status(True, self._switch_id)
self._device.set_dps(True, self._switch_id)
def turn_off(self, **kwargs):
"""Turn Tuya switch off."""
self._device.set_status(False, self._switch_id)
self._device.set_dps(False, self._switch_id)
def update(self):
"""Get state of Tuya switch."""