Merge branch 'master' into pytuya_refactoring
This commit is contained in:
@@ -22,132 +22,109 @@ switch:
|
||||
sw02:
|
||||
name: usb_plug
|
||||
friendly_name: USB Plug
|
||||
id: 7
|
||||
id: 7
|
||||
"""
|
||||
import logging
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.switch import SwitchEntity, PLATFORM_SCHEMA
|
||||
from homeassistant.const import (CONF_HOST, CONF_ID, CONF_SWITCHES, CONF_FRIENDLY_NAME, CONF_ICON, CONF_NAME)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
from time import time, sleep
|
||||
from threading import Lock
|
||||
|
||||
import voluptuous as vol
|
||||
|
||||
from homeassistant.components.switch import (
|
||||
SwitchEntity,
|
||||
PLATFORM_SCHEMA,
|
||||
)
|
||||
from homeassistant.const import (
|
||||
CONF_ID,
|
||||
CONF_SWITCHES,
|
||||
CONF_FRIENDLY_NAME,
|
||||
CONF_NAME,
|
||||
)
|
||||
import homeassistant.helpers.config_validation as cv
|
||||
|
||||
from . import BASE_PLATFORM_SCHEMA, prepare_setup_entities, import_from_yaml
|
||||
from .const import (
|
||||
ATTR_CURRENT,
|
||||
ATTR_CURRENT_CONSUMPTION,
|
||||
ATTR_VOLTAGE,
|
||||
CONF_CURRENT,
|
||||
CONF_CURRENT_CONSUMPTION,
|
||||
CONF_VOLTAGE,
|
||||
)
|
||||
from .pytuya import TuyaDevice
|
||||
|
||||
_LOGGER = logging.getLogger(__name__)
|
||||
|
||||
CONF_DEVICE_ID = 'device_id'
|
||||
CONF_LOCAL_KEY = 'local_key'
|
||||
CONF_PROTOCOL_VERSION = 'protocol_version'
|
||||
CONF_CURRENT = 'current'
|
||||
CONF_CURRENT_CONSUMPTION = 'current_consumption'
|
||||
CONF_VOLTAGE = 'voltage'
|
||||
PLATFORM = "switch"
|
||||
|
||||
DEFAULT_ID = '1'
|
||||
DEFAULT_PROTOCOL_VERSION = 3.3
|
||||
DEFAULT_ID = "1"
|
||||
|
||||
ATTR_CURRENT = 'current'
|
||||
ATTR_CURRENT_CONSUMPTION = 'current_consumption'
|
||||
ATTR_VOLTAGE = 'voltage'
|
||||
# TODO: This will eventully merge with flow_schema
|
||||
SWITCH_SCHEMA = vol.Schema(
|
||||
{
|
||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||
vol.Optional(CONF_NAME): cv.string, # Deprecated: not used
|
||||
vol.Required(CONF_FRIENDLY_NAME): cv.string,
|
||||
vol.Optional(CONF_CURRENT, default="-1"): cv.string,
|
||||
vol.Optional(CONF_CURRENT_CONSUMPTION, default="-1"): cv.string,
|
||||
vol.Optional(CONF_VOLTAGE, default="-1"): cv.string,
|
||||
}
|
||||
)
|
||||
|
||||
SWITCH_SCHEMA = vol.Schema({
|
||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||
vol.Required(CONF_NAME): cv.string,
|
||||
vol.Required(CONF_FRIENDLY_NAME): cv.string,
|
||||
vol.Optional(CONF_CURRENT, default='-1'): cv.string,
|
||||
vol.Optional(CONF_CURRENT_CONSUMPTION, default='-1'): cv.string,
|
||||
vol.Optional(CONF_VOLTAGE, default='-1'): cv.string,
|
||||
})
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(BASE_PLATFORM_SCHEMA).extend(
|
||||
{
|
||||
vol.Optional(CONF_CURRENT, default="-1"): cv.string,
|
||||
vol.Optional(CONF_CURRENT_CONSUMPTION, default="-1"): cv.string,
|
||||
vol.Optional(CONF_VOLTAGE, default="-1"): cv.string,
|
||||
vol.Optional(CONF_SWITCHES, default={}): vol.Schema({cv.slug: SWITCH_SCHEMA}),
|
||||
}
|
||||
)
|
||||
|
||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
||||
vol.Optional(CONF_ICON): cv.icon,
|
||||
vol.Required(CONF_HOST): cv.string,
|
||||
vol.Required(CONF_DEVICE_ID): cv.string,
|
||||
vol.Required(CONF_LOCAL_KEY): cv.string,
|
||||
vol.Required(CONF_NAME): cv.string,
|
||||
vol.Required(CONF_FRIENDLY_NAME): cv.string,
|
||||
vol.Required(CONF_PROTOCOL_VERSION, default=DEFAULT_PROTOCOL_VERSION): vol.Coerce(float),
|
||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||
vol.Optional(CONF_CURRENT, default='-1'): cv.string,
|
||||
vol.Optional(CONF_CURRENT_CONSUMPTION, default='-1'): cv.string,
|
||||
vol.Optional(CONF_VOLTAGE, default='-1'): cv.string,
|
||||
vol.Optional(CONF_SWITCHES, default={}):
|
||||
vol.Schema({cv.slug: SWITCH_SCHEMA}),
|
||||
})
|
||||
|
||||
def flow_schema(dps):
|
||||
"""Return schema used in config flow."""
|
||||
return {
|
||||
vol.Optional(CONF_CURRENT): vol.In(dps),
|
||||
vol.Optional(CONF_CURRENT_CONSUMPTION): vol.In(dps),
|
||||
vol.Optional(CONF_VOLTAGE): vol.In(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, PLATFORM
|
||||
)
|
||||
if not entities_to_setup:
|
||||
return
|
||||
|
||||
switches = []
|
||||
for device_config in entities_to_setup:
|
||||
switches.append(
|
||||
LocaltuyaSwitch(
|
||||
TuyaCache(device),
|
||||
device_config[CONF_FRIENDLY_NAME],
|
||||
device_config[CONF_ID],
|
||||
device_config.get(CONF_CURRENT),
|
||||
device_config.get(CONF_CURRENT_CONSUMPTION),
|
||||
device_config.get(CONF_VOLTAGE),
|
||||
)
|
||||
)
|
||||
|
||||
async_add_entities(switches, True)
|
||||
|
||||
|
||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||
"""Set up of the Tuya switch."""
|
||||
from . import pytuya
|
||||
return import_from_yaml(hass, config, PLATFORM)
|
||||
|
||||
devices = config.get(CONF_SWITCHES)
|
||||
|
||||
switches = []
|
||||
pytuyadevice = pytuya.TuyaDevice(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:
|
||||
for object_id, device_config in devices.items():
|
||||
dps = {}
|
||||
dps[device_config.get(CONF_ID)]=None
|
||||
if device_config.get(CONF_CURRENT) != '-1':
|
||||
dps[device_config.get(CONF_CURRENT)]=None
|
||||
if device_config.get(CONF_CURRENT_CONSUMPTION) != '-1':
|
||||
dps[device_config.get(CONF_CURRENT_CONSUMPTION)]=None
|
||||
if device_config.get(CONF_VOLTAGE) != '-1':
|
||||
dps[device_config.get(CONF_VOLTAGE)]=None
|
||||
pytuyadevice.set_dpsUsed(dps)
|
||||
|
||||
outlet_device = TuyaCache(pytuyadevice)
|
||||
switches.append(
|
||||
LocaltuyaSwitch(
|
||||
outlet_device,
|
||||
device_config.get(CONF_NAME),
|
||||
device_config.get(CONF_FRIENDLY_NAME, object_id),
|
||||
device_config.get(CONF_ICON),
|
||||
device_config.get(CONF_ID),
|
||||
device_config.get(CONF_CURRENT),
|
||||
device_config.get(CONF_CURRENT_CONSUMPTION),
|
||||
device_config.get(CONF_VOLTAGE)
|
||||
)
|
||||
)
|
||||
|
||||
print('Setup localtuya subswitch [{}] with device ID [{}] '.format(device_config.get(CONF_FRIENDLY_NAME, object_id), device_config.get(CONF_ID)))
|
||||
_LOGGER.info("Setup localtuya subswitch %s with device ID %s ", device_config.get(CONF_FRIENDLY_NAME, object_id), device_config.get(CONF_ID) )
|
||||
else:
|
||||
dps = {}
|
||||
dps[config.get(CONF_ID)]=None
|
||||
if config.get(CONF_CURRENT) != '-1':
|
||||
dps[config.get(CONF_CURRENT)]=None
|
||||
if config.get(CONF_CURRENT_CONSUMPTION) != '-1':
|
||||
dps[config.get(CONF_CURRENT_CONSUMPTION)]=None
|
||||
if config.get(CONF_VOLTAGE) != '-1':
|
||||
dps[config.get(CONF_VOLTAGE)]=None
|
||||
pytuyadevice.set_dpsUsed(dps)
|
||||
outlet_device = TuyaCache(pytuyadevice)
|
||||
switches.append(
|
||||
LocaltuyaSwitch(
|
||||
outlet_device,
|
||||
config.get(CONF_NAME),
|
||||
config.get(CONF_FRIENDLY_NAME),
|
||||
config.get(CONF_ICON),
|
||||
config.get(CONF_ID),
|
||||
config.get(CONF_CURRENT),
|
||||
config.get(CONF_CURRENT_CONSUMPTION),
|
||||
config.get(CONF_VOLTAGE)
|
||||
)
|
||||
)
|
||||
|
||||
print('Setup localtuya switch [{}] with device ID [{}] '.format(config.get(CONF_FRIENDLY_NAME), config.get(CONF_ID)))
|
||||
_LOGGER.info("Setup localtuya switch %s with device ID %s ", config.get(CONF_FRIENDLY_NAME), config.get(CONF_ID) )
|
||||
|
||||
add_devices(switches, True)
|
||||
|
||||
class TuyaCache:
|
||||
"""Cache wrapper for pytuya.TuyaDevice"""
|
||||
|
||||
def __init__(self, device):
|
||||
"""Initialize the cache."""
|
||||
self._cached_status = ''
|
||||
self._cached_status = ""
|
||||
self._cached_status_time = 0
|
||||
self._device = device
|
||||
self._lock = Lock()
|
||||
@@ -163,26 +140,37 @@ class TuyaCache:
|
||||
status = self._device.status()
|
||||
return status
|
||||
except Exception:
|
||||
print('Failed to update status of device [{}]'.format(self._device.address))
|
||||
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
|
||||
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 = ""
|
||||
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 )
|
||||
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.")
|
||||
|
||||
# raise ConnectionError("Failed to set status.")
|
||||
|
||||
def status(self):
|
||||
"""Get state of Tuya switch and cache the results."""
|
||||
@@ -200,19 +188,30 @@ class TuyaCache:
|
||||
class LocaltuyaSwitch(SwitchEntity):
|
||||
"""Representation of a Tuya switch."""
|
||||
|
||||
def __init__(self, device, name, friendly_name, icon, switchid, attr_current, attr_consumption, attr_voltage):
|
||||
def __init__(
|
||||
self,
|
||||
device,
|
||||
friendly_name,
|
||||
switchid,
|
||||
attr_current,
|
||||
attr_consumption,
|
||||
attr_voltage,
|
||||
):
|
||||
"""Initialize the Tuya switch."""
|
||||
self._device = device
|
||||
self._name = friendly_name
|
||||
self._available = False
|
||||
self._icon = icon
|
||||
self._switch_id = switchid
|
||||
self._attr_current = attr_current
|
||||
self._attr_consumption = attr_consumption
|
||||
self._attr_voltage = attr_voltage
|
||||
self._status = self._device.status()
|
||||
self._state = self._status['dps'][self._switch_id]
|
||||
print('Initialized tuya switch [{}] with switch status [{}] and state [{}]'.format(self._name, self._status, self._state))
|
||||
self._status = None
|
||||
self._state = None
|
||||
print(
|
||||
"Initialized tuya switch [{}] with switch status [{}] and state [{}]".format(
|
||||
self._name, self._status, self._state
|
||||
)
|
||||
)
|
||||
|
||||
@property
|
||||
def name(self):
|
||||
@@ -237,23 +236,16 @@ class LocaltuyaSwitch(SwitchEntity):
|
||||
@property
|
||||
def device_state_attributes(self):
|
||||
attrs = {}
|
||||
try:
|
||||
attrs[ATTR_CURRENT] = "{}".format(self._status['dps'][self._attr_current])
|
||||
attrs[ATTR_CURRENT_CONSUMPTION] = "{}".format(self._status['dps'][self._attr_consumption]/10)
|
||||
attrs[ATTR_VOLTAGE] = "{}".format(self._status['dps'][self._attr_voltage]/10)
|
||||
# print('attrs[ATTR_CURRENT]: [{}]'.format(attrs[ATTR_CURRENT]))
|
||||
# print('attrs[ATTR_CURRENT_CONSUMPTION]: [{}]'.format(attrs[ATTR_CURRENT_CONSUMPTION]))
|
||||
# print('attrs[ATTR_VOLTAGE]: [{}]'.format(attrs[ATTR_VOLTAGE]))
|
||||
|
||||
except KeyError:
|
||||
pass
|
||||
if self._attr_current:
|
||||
attrs[ATTR_CURRENT] = self._status["dps"][self._attr_current]
|
||||
if self._attr_consumption:
|
||||
attrs[ATTR_CURRENT_CONSUMPTION] = (
|
||||
self._status["dps"][self._attr_consumption] / 10
|
||||
)
|
||||
if self._attr_voltage:
|
||||
attrs[ATTR_VOLTAGE] = self._status["dps"][self._attr_voltage] / 10
|
||||
return attrs
|
||||
|
||||
@property
|
||||
def icon(self):
|
||||
"""Return the icon."""
|
||||
return self._icon
|
||||
|
||||
def turn_on(self, **kwargs):
|
||||
"""Turn Tuya switch on."""
|
||||
self._device.set_dps(True, self._switch_id)
|
||||
@@ -266,7 +258,7 @@ class LocaltuyaSwitch(SwitchEntity):
|
||||
"""Get state of Tuya switch."""
|
||||
try:
|
||||
self._status = self._device.status()
|
||||
self._state = self._status['dps'][self._switch_id]
|
||||
self._state = self._status["dps"][self._switch_id]
|
||||
except Exception:
|
||||
self._available = False
|
||||
else:
|
||||
|
Reference in New Issue
Block a user