Merge branch 'postlund-light_config_flow'
This commit is contained in:
@@ -1,13 +1,71 @@
|
|||||||
"""The LocalTuya integration integration."""
|
"""The LocalTuya integration integration."""
|
||||||
import asyncio
|
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
|
||||||
from homeassistant.config_entries import ConfigEntry
|
from homeassistant.config_entries import SOURCE_IMPORT, ConfigEntry
|
||||||
from homeassistant.core import HomeAssistant
|
from homeassistant.core import HomeAssistant
|
||||||
from homeassistant.const import CONF_PLATFORM
|
from homeassistant.const import (
|
||||||
|
CONF_DEVICE_ID,
|
||||||
|
CONF_ID,
|
||||||
|
CONF_ICON,
|
||||||
|
CONF_NAME,
|
||||||
|
CONF_FRIENDLY_NAME,
|
||||||
|
CONF_HOST,
|
||||||
|
CONF_PLATFORM,
|
||||||
|
CONF_ENTITIES,
|
||||||
|
)
|
||||||
|
import homeassistant.helpers.config_validation as cv
|
||||||
|
|
||||||
from .const import DOMAIN, PLATFORMS
|
from . import pytuya
|
||||||
|
from .const import CONF_LOCAL_KEY, CONF_PROTOCOL_VERSION, DOMAIN, PLATFORMS
|
||||||
|
|
||||||
|
|
||||||
|
DEFAULT_ID = "1"
|
||||||
|
DEFAULT_PROTOCOL_VERSION = 3.3
|
||||||
|
|
||||||
|
BASE_PLATFORM_SCHEMA = {
|
||||||
|
vol.Optional(CONF_ICON): cv.icon, # Deprecated: not used
|
||||||
|
vol.Required(CONF_HOST): cv.string,
|
||||||
|
vol.Required(CONF_DEVICE_ID): cv.string,
|
||||||
|
vol.Required(CONF_LOCAL_KEY): cv.string,
|
||||||
|
vol.Optional(CONF_NAME): cv.string, # Deprecated: not used
|
||||||
|
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,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def prepare_setup_entities(config_entry, platform):
|
||||||
|
"""Prepare ro setup entities for a platform."""
|
||||||
|
entities_to_setup = [
|
||||||
|
entity
|
||||||
|
for entity in config_entry.data[CONF_ENTITIES]
|
||||||
|
if entity[CONF_PLATFORM] == platform
|
||||||
|
]
|
||||||
|
if not entities_to_setup:
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
device = pytuya.BulbDevice(
|
||||||
|
config_entry.data[CONF_DEVICE_ID],
|
||||||
|
config_entry.data[CONF_HOST],
|
||||||
|
config_entry.data[CONF_LOCAL_KEY],
|
||||||
|
)
|
||||||
|
device.set_version(float(config_entry.data[CONF_PROTOCOL_VERSION]))
|
||||||
|
device.set_dpsUsed({})
|
||||||
|
return device, entities_to_setup
|
||||||
|
|
||||||
|
|
||||||
|
def import_from_yaml(hass, config, platform):
|
||||||
|
"""Import configuration from YAML."""
|
||||||
|
config[CONF_PLATFORM] = platform
|
||||||
|
hass.async_create_task(
|
||||||
|
hass.config_entries.flow.async_init(
|
||||||
|
DOMAIN, context={"source": SOURCE_IMPORT}, data=config
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
async def async_setup(hass: HomeAssistant, config: dict):
|
async def async_setup(hass: HomeAssistant, config: dict):
|
||||||
|
@@ -44,27 +44,35 @@ PICK_ENTITY_SCHEMA = vol.Schema(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def platform_schema(dps, additional_fields):
|
def dps_string_list(dps_data):
|
||||||
|
"""Return list of friendly DPS values."""
|
||||||
|
return [f"{id} (value: {value})" for id, value in dps_data.items()]
|
||||||
|
|
||||||
|
|
||||||
|
def platform_schema(dps_strings, schema):
|
||||||
"""Generate input validation schema for a platform."""
|
"""Generate input validation schema for a platform."""
|
||||||
dps_list = vol.In([f"{id} (value: {value})" for id, value in dps.items()])
|
|
||||||
return vol.Schema(
|
return vol.Schema(
|
||||||
{
|
{
|
||||||
vol.Required(CONF_ID): dps_list,
|
vol.Required(CONF_ID): vol.In(dps_strings),
|
||||||
vol.Required(CONF_FRIENDLY_NAME): str,
|
vol.Required(CONF_FRIENDLY_NAME): str,
|
||||||
}
|
}
|
||||||
).extend({conf: dps_list for conf in additional_fields})
|
).extend(schema)
|
||||||
|
|
||||||
|
|
||||||
def strip_dps_values(user_input, fields):
|
def strip_dps_values(user_input, dps_strings):
|
||||||
"""Remove values and keep only index for DPS config items."""
|
"""Remove values and keep only index for DPS config items."""
|
||||||
for field in [CONF_ID] + fields:
|
stripped = {}
|
||||||
user_input[field] = user_input[field].split(" ")[0]
|
for field, value in user_input.items():
|
||||||
return user_input
|
if value in dps_strings:
|
||||||
|
stripped[field] = user_input[field].split(" ")[0]
|
||||||
|
else:
|
||||||
|
stripped[field] = user_input[field]
|
||||||
|
return stripped
|
||||||
|
|
||||||
|
|
||||||
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.OutletDevice(
|
pytuyadevice = pytuya.Device(
|
||||||
data[CONF_DEVICE_ID], data[CONF_HOST], data[CONF_LOCAL_KEY]
|
data[CONF_DEVICE_ID], data[CONF_HOST], data[CONF_LOCAL_KEY]
|
||||||
)
|
)
|
||||||
pytuyadevice.set_version(float(data[CONF_PROTOCOL_VERSION]))
|
pytuyadevice.set_version(float(data[CONF_PROTOCOL_VERSION]))
|
||||||
@@ -75,7 +83,7 @@ async def validate_input(hass: core.HomeAssistant, data):
|
|||||||
raise CannotConnect
|
raise CannotConnect
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise InvalidAuth
|
raise InvalidAuth
|
||||||
return data["dps"]
|
return dps_string_list(data["dps"])
|
||||||
|
|
||||||
|
|
||||||
class LocaltuyaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
class LocaltuyaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||||
@@ -87,9 +95,9 @@ class LocaltuyaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
def __init__(self):
|
def __init__(self):
|
||||||
"""Initialize a new LocaltuyaConfigFlow."""
|
"""Initialize a new LocaltuyaConfigFlow."""
|
||||||
self.basic_info = None
|
self.basic_info = None
|
||||||
self.dps_data = None
|
self.dps_strings = []
|
||||||
self.platform = None
|
self.platform = None
|
||||||
self.platform_dps_fields = None
|
self.platform_schema = None
|
||||||
self.entities = []
|
self.entities = []
|
||||||
|
|
||||||
async def async_step_user(self, user_input=None):
|
async def async_step_user(self, user_input=None):
|
||||||
@@ -101,7 +109,7 @@ class LocaltuyaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
self.basic_info = user_input
|
self.basic_info = user_input
|
||||||
self.dps_data = await validate_input(self.hass, user_input)
|
self.dps_strings = await validate_input(self.hass, user_input)
|
||||||
return await self.async_step_pick_entity_type()
|
return await self.async_step_pick_entity_type()
|
||||||
except CannotConnect:
|
except CannotConnect:
|
||||||
errors["base"] = "cannot_connect"
|
errors["base"] = "cannot_connect"
|
||||||
@@ -144,16 +152,14 @@ class LocaltuyaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
)
|
)
|
||||||
if not already_configured:
|
if not already_configured:
|
||||||
user_input[CONF_PLATFORM] = self.platform
|
user_input[CONF_PLATFORM] = self.platform
|
||||||
self.entities.append(
|
self.entities.append(strip_dps_values(user_input, self.dps_strings))
|
||||||
strip_dps_values(user_input, self.platform_dps_fields)
|
|
||||||
)
|
|
||||||
return await self.async_step_pick_entity_type()
|
return await self.async_step_pick_entity_type()
|
||||||
|
|
||||||
errors["base"] = "entity_already_configured"
|
errors["base"] = "entity_already_configured"
|
||||||
|
|
||||||
return self.async_show_form(
|
return self.async_show_form(
|
||||||
step_id="add_entity",
|
step_id="add_entity",
|
||||||
data_schema=platform_schema(self.dps_data, self.platform_dps_fields),
|
data_schema=platform_schema(self.dps_strings, self.platform_schema),
|
||||||
errors=errors,
|
errors=errors,
|
||||||
description_placeholders={"platform": self.platform},
|
description_placeholders={"platform": self.platform},
|
||||||
)
|
)
|
||||||
@@ -167,14 +173,14 @@ class LocaltuyaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
CONF_FRIENDLY_NAME: conf[CONF_FRIENDLY_NAME],
|
CONF_FRIENDLY_NAME: conf[CONF_FRIENDLY_NAME],
|
||||||
CONF_PLATFORM: self.platform,
|
CONF_PLATFORM: self.platform,
|
||||||
}
|
}
|
||||||
for field in self.platform_dps_fields:
|
for field in self.platform_schema.keys():
|
||||||
converted[str(field)] = conf[field]
|
converted[str(field)] = conf[field]
|
||||||
return converted
|
return converted
|
||||||
|
|
||||||
await self.async_set_unique_id(user_input[CONF_DEVICE_ID])
|
await self.async_set_unique_id(user_input[CONF_DEVICE_ID])
|
||||||
self._set_platform(user_input[CONF_PLATFORM])
|
self._set_platform(user_input[CONF_PLATFORM], [])
|
||||||
|
|
||||||
if len(user_input[CONF_SWITCHES]) > 0:
|
if len(user_input.get(CONF_SWITCHES, [])) > 0:
|
||||||
for switch_conf in user_input[CONF_SWITCHES].values():
|
for switch_conf in user_input[CONF_SWITCHES].values():
|
||||||
self.entities.append(_convert_entity(switch_conf))
|
self.entities.append(_convert_entity(switch_conf))
|
||||||
else:
|
else:
|
||||||
@@ -194,7 +200,9 @@ class LocaltuyaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
|||||||
def _set_platform(self, platform):
|
def _set_platform(self, platform):
|
||||||
integration_module = ".".join(__name__.split(".")[:-1])
|
integration_module = ".".join(__name__.split(".")[:-1])
|
||||||
self.platform = platform
|
self.platform = platform
|
||||||
self.platform_dps_fields = import_module("." + platform, integration_module).DPS_FIELDS
|
self.platform_schema = import_module(
|
||||||
|
"." + platform, integration_module
|
||||||
|
).flow_schema(self.dps_strings)
|
||||||
|
|
||||||
|
|
||||||
class CannotConnect(exceptions.HomeAssistantError):
|
class CannotConnect(exceptions.HomeAssistantError):
|
||||||
|
@@ -13,4 +13,4 @@ CONF_VOLTAGE = "voltage"
|
|||||||
DOMAIN = "localtuya"
|
DOMAIN = "localtuya"
|
||||||
|
|
||||||
# Platforms in this list must support config flows
|
# Platforms in this list must support config flows
|
||||||
PLATFORMS = ["switch"]
|
PLATFORMS = ["light", "switch"]
|
||||||
|
@@ -12,12 +12,15 @@ light:
|
|||||||
friendly_name: This Light
|
friendly_name: This Light
|
||||||
protocol_version: 3.3
|
protocol_version: 3.3
|
||||||
"""
|
"""
|
||||||
import voluptuous as vol
|
import socket
|
||||||
from homeassistant.const import (CONF_HOST, CONF_ID, CONF_SWITCHES, CONF_FRIENDLY_NAME, CONF_ICON, CONF_NAME)
|
import logging
|
||||||
import homeassistant.helpers.config_validation as cv
|
|
||||||
from time import time, sleep
|
from time import time, sleep
|
||||||
from threading import Lock
|
from threading import Lock
|
||||||
import logging
|
|
||||||
|
from homeassistant.const import (
|
||||||
|
CONF_ID,
|
||||||
|
CONF_FRIENDLY_NAME,
|
||||||
|
)
|
||||||
from homeassistant.components.light import (
|
from homeassistant.components.light import (
|
||||||
ATTR_BRIGHTNESS,
|
ATTR_BRIGHTNESS,
|
||||||
ATTR_COLOR_TEMP,
|
ATTR_COLOR_TEMP,
|
||||||
@@ -26,64 +29,56 @@ from homeassistant.components.light import (
|
|||||||
SUPPORT_COLOR,
|
SUPPORT_COLOR,
|
||||||
SUPPORT_COLOR_TEMP,
|
SUPPORT_COLOR_TEMP,
|
||||||
LightEntity,
|
LightEntity,
|
||||||
PLATFORM_SCHEMA
|
PLATFORM_SCHEMA,
|
||||||
)
|
)
|
||||||
from homeassistant.util import color as colorutil
|
from homeassistant.util import color as colorutil
|
||||||
import socket
|
|
||||||
|
|
||||||
REQUIREMENTS = ['pytuya>=7.1.0']
|
from . import BASE_PLATFORM_SCHEMA, import_from_yaml, prepare_setup_entities
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
CONF_DEVICE_ID = 'device_id'
|
|
||||||
CONF_LOCAL_KEY = 'local_key'
|
|
||||||
CONF_PROTOCOL_VERSION = 'protocol_version'
|
|
||||||
# IMPORTANT, id is used as key for state and turning on and off, 1 was fine switched apparently but my bulbs need 20, other feature attributes count up from this, e.g. 21 mode, 22 brightnes etc, see my pytuya modification.
|
|
||||||
DEFAULT_ID = '1'
|
|
||||||
DEFAULT_PROTOCOL_VERSION = 3.3
|
|
||||||
MIN_MIRED = 153
|
MIN_MIRED = 153
|
||||||
MAX_MIRED = 370
|
MAX_MIRED = 370
|
||||||
UPDATE_RETRY_LIMIT = 3
|
UPDATE_RETRY_LIMIT = 3
|
||||||
|
|
||||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(BASE_PLATFORM_SCHEMA)
|
||||||
vol.Optional(CONF_ICON): cv.icon,
|
|
||||||
vol.Required(CONF_HOST): cv.string,
|
|
||||||
vol.Required(CONF_DEVICE_ID): cv.string,
|
def flow_schema(dps):
|
||||||
vol.Required(CONF_LOCAL_KEY): cv.string,
|
"""Return schema used in config flow."""
|
||||||
vol.Required(CONF_NAME): cv.string,
|
return {}
|
||||||
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,
|
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||||
})
|
"""Setup a Tuya switch based on a config entry."""
|
||||||
log = logging.getLogger(__name__)
|
device, entities_to_setup = prepare_setup_entities(config_entry, "light")
|
||||||
log.setLevel(level=logging.DEBUG) # Debug hack!
|
if not entities_to_setup:
|
||||||
|
return
|
||||||
|
|
||||||
|
lights = []
|
||||||
|
for device_config in entities_to_setup:
|
||||||
|
lights.append(
|
||||||
|
TuyaDevice(
|
||||||
|
TuyaCache(device),
|
||||||
|
device_config[CONF_FRIENDLY_NAME],
|
||||||
|
device_config[CONF_ID],
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
async_add_entities(lights, True)
|
||||||
|
|
||||||
|
|
||||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
"""Set up of the Tuya switch."""
|
"""Set up of the Tuya switch."""
|
||||||
from . import pytuya
|
return import_from_yaml(hass, config, "light")
|
||||||
|
|
||||||
lights = []
|
|
||||||
pytuyadevice = pytuya.BulbDevice(config.get(CONF_DEVICE_ID), config.get(CONF_HOST), config.get(CONF_LOCAL_KEY))
|
|
||||||
pytuyadevice.set_version(float(config.get(CONF_PROTOCOL_VERSION)))
|
|
||||||
|
|
||||||
bulb_device = TuyaCache(pytuyadevice)
|
|
||||||
lights.append(
|
|
||||||
TuyaDevice(
|
|
||||||
bulb_device,
|
|
||||||
config.get(CONF_NAME),
|
|
||||||
config.get(CONF_FRIENDLY_NAME),
|
|
||||||
config.get(CONF_ICON),
|
|
||||||
config.get(CONF_ID)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
add_devices(lights)
|
|
||||||
|
|
||||||
class TuyaCache:
|
class TuyaCache:
|
||||||
"""Cache wrapper for pytuya.BulbDevice"""
|
"""Cache wrapper for pytuya.BulbDevice"""
|
||||||
|
|
||||||
def __init__(self, device):
|
def __init__(self, device):
|
||||||
"""Initialize the cache."""
|
"""Initialize the cache."""
|
||||||
self._cached_status = ''
|
self._cached_status = ""
|
||||||
self._cached_status_time = 0
|
self._cached_status_time = 0
|
||||||
self._device = device
|
self._device = device
|
||||||
self._lock = Lock()
|
self._lock = Lock()
|
||||||
@@ -96,41 +91,31 @@ class TuyaCache:
|
|||||||
def __get_status(self, switchid):
|
def __get_status(self, switchid):
|
||||||
for _ in range(UPDATE_RETRY_LIMIT):
|
for _ in range(UPDATE_RETRY_LIMIT):
|
||||||
try:
|
try:
|
||||||
status = self._device.status()['dps'][switchid]
|
return self._device.status()["dps"][switchid]
|
||||||
return status
|
except (ConnectionError, socket.timeout):
|
||||||
except ConnectionError:
|
|
||||||
pass
|
pass
|
||||||
except socket.timeout:
|
_LOGGER.warning("Failed to get status after %d tries", UPDATE_RETRY_LIMIT)
|
||||||
pass
|
|
||||||
log.warn(
|
|
||||||
"Failed to get status after {} tries".format(UPDATE_RETRY_LIMIT))
|
|
||||||
|
|
||||||
def set_status(self, state, switchid):
|
def set_status(self, state, switchid):
|
||||||
"""Change the Tuya switch status and clear the cache."""
|
"""Change the Tuya switch status and clear the cache."""
|
||||||
self._cached_status = ''
|
self._cached_status = ""
|
||||||
self._cached_status_time = 0
|
self._cached_status_time = 0
|
||||||
for _ in range(UPDATE_RETRY_LIMIT):
|
for _ in range(UPDATE_RETRY_LIMIT):
|
||||||
try:
|
try:
|
||||||
return self._device.set_status(state, switchid)
|
return self._device.set_status(state, switchid)
|
||||||
except ConnectionError:
|
except (ConnectionError, socket.timeout):
|
||||||
pass
|
pass
|
||||||
except socket.timeout:
|
_LOGGER.warning("Failed to set status after %d tries", UPDATE_RETRY_LIMIT)
|
||||||
pass
|
|
||||||
log.warn(
|
|
||||||
"Failed to set status after {} tries".format(UPDATE_RETRY_LIMIT))
|
|
||||||
|
|
||||||
def status(self, switchid):
|
def status(self, switchid):
|
||||||
"""Get state of Tuya switch and cache the results."""
|
"""Get state of Tuya switch and cache the results."""
|
||||||
self._lock.acquire()
|
with self._lock:
|
||||||
try:
|
|
||||||
now = time()
|
now = time()
|
||||||
if not self._cached_status or now - self._cached_status_time > 15:
|
if not self._cached_status or now - self._cached_status_time > 15:
|
||||||
sleep(0.5)
|
sleep(0.5)
|
||||||
self._cached_status = self.__get_status(switchid)
|
self._cached_status = self.__get_status(switchid)
|
||||||
self._cached_status_time = time()
|
self._cached_status_time = time()
|
||||||
return self._cached_status
|
return self._cached_status
|
||||||
finally:
|
|
||||||
self._lock.release()
|
|
||||||
|
|
||||||
def cached_status(self):
|
def cached_status(self):
|
||||||
return self._cached_status
|
return self._cached_status
|
||||||
@@ -145,67 +130,52 @@ class TuyaCache:
|
|||||||
for _ in range(UPDATE_RETRY_LIMIT):
|
for _ in range(UPDATE_RETRY_LIMIT):
|
||||||
try:
|
try:
|
||||||
return self._device.brightness()
|
return self._device.brightness()
|
||||||
except ConnectionError:
|
except (ConnectionError, socket.timeout):
|
||||||
pass
|
pass
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return "999"
|
return "999"
|
||||||
except socket.timeout:
|
_LOGGER.warning("Failed to get brightness after %d tries", UPDATE_RETRY_LIMIT)
|
||||||
pass
|
|
||||||
log.warn(
|
|
||||||
"Failed to get brightness after {} tries".format(UPDATE_RETRY_LIMIT))
|
|
||||||
|
|
||||||
def color_temp(self):
|
def color_temp(self):
|
||||||
for _ in range(UPDATE_RETRY_LIMIT):
|
for _ in range(UPDATE_RETRY_LIMIT):
|
||||||
try:
|
try:
|
||||||
return self._device.colourtemp()
|
return self._device.colourtemp()
|
||||||
except ConnectionError:
|
except (ConnectionError, socket.timeout):
|
||||||
pass
|
pass
|
||||||
except KeyError:
|
except KeyError:
|
||||||
return "999"
|
return "999"
|
||||||
except socket.timeout:
|
_LOGGER.warning("Failed to get color temp after %d tries", UPDATE_RETRY_LIMIT)
|
||||||
pass
|
|
||||||
log.warn(
|
|
||||||
"Failed to get color temp after {} tries".format(UPDATE_RETRY_LIMIT))
|
|
||||||
|
|
||||||
def set_brightness(self, brightness):
|
def set_brightness(self, brightness):
|
||||||
for _ in range(UPDATE_RETRY_LIMIT):
|
for _ in range(UPDATE_RETRY_LIMIT):
|
||||||
try:
|
try:
|
||||||
return self._device.set_brightness(brightness)
|
return self._device.set_brightness(brightness)
|
||||||
except ConnectionError:
|
except (ConnectionError, KeyError, socket.timeout):
|
||||||
pass
|
pass
|
||||||
except KeyError:
|
_LOGGER.warning("Failed to set brightness after %d tries", UPDATE_RETRY_LIMIT)
|
||||||
pass
|
|
||||||
except socket.timeout:
|
|
||||||
pass
|
|
||||||
log.warn(
|
|
||||||
"Failed to set brightness after {} tries".format(UPDATE_RETRY_LIMIT))
|
|
||||||
|
|
||||||
def set_color_temp(self, color_temp):
|
def set_color_temp(self, color_temp):
|
||||||
for _ in range(UPDATE_RETRY_LIMIT):
|
for _ in range(UPDATE_RETRY_LIMIT):
|
||||||
try:
|
try:
|
||||||
return self._device.set_colourtemp(color_temp)
|
return self._device.set_colourtemp(color_temp)
|
||||||
except ConnectionError:
|
except (ConnectionError, KeyError, socket.timeout):
|
||||||
pass
|
pass
|
||||||
except KeyError:
|
_LOGGER.warning("Failed to set color temp after %d tries", UPDATE_RETRY_LIMIT)
|
||||||
pass
|
|
||||||
except socket.timeout:
|
|
||||||
pass
|
|
||||||
log.warn(
|
|
||||||
"Failed to set color temp after {} tries".format(UPDATE_RETRY_LIMIT))
|
|
||||||
|
|
||||||
def state(self):
|
def state(self):
|
||||||
self._device.state();
|
self._device.state()
|
||||||
|
|
||||||
def turn_on(self):
|
def turn_on(self):
|
||||||
self._device.turn_on();
|
self._device.turn_on()
|
||||||
|
|
||||||
def turn_off(self):
|
def turn_off(self):
|
||||||
self._device.turn_off();
|
self._device.turn_off()
|
||||||
|
|
||||||
|
|
||||||
class TuyaDevice(LightEntity):
|
class TuyaDevice(LightEntity):
|
||||||
"""Representation of a Tuya switch."""
|
"""Representation of a Tuya switch."""
|
||||||
|
|
||||||
def __init__(self, device, name, friendly_name, icon, bulbid):
|
def __init__(self, device, friendly_name, bulbid):
|
||||||
"""Initialize the Tuya switch."""
|
"""Initialize the Tuya switch."""
|
||||||
self._device = device
|
self._device = device
|
||||||
self._available = False
|
self._available = False
|
||||||
@@ -213,7 +183,6 @@ class TuyaDevice(LightEntity):
|
|||||||
self._state = False
|
self._state = False
|
||||||
self._brightness = 127
|
self._brightness = 127
|
||||||
self._color_temp = 127
|
self._color_temp = 127
|
||||||
self._icon = icon
|
|
||||||
self._bulb_id = bulbid
|
self._bulb_id = bulbid
|
||||||
|
|
||||||
@property
|
@property
|
||||||
@@ -236,11 +205,6 @@ class TuyaDevice(LightEntity):
|
|||||||
"""Check if Tuya switch is on."""
|
"""Check if Tuya switch is on."""
|
||||||
return self._state
|
return self._state
|
||||||
|
|
||||||
@property
|
|
||||||
def icon(self):
|
|
||||||
"""Return the icon."""
|
|
||||||
return self._icon
|
|
||||||
|
|
||||||
def update(self):
|
def update(self):
|
||||||
"""Get state of Tuya switch."""
|
"""Get state of Tuya switch."""
|
||||||
try:
|
try:
|
||||||
@@ -294,7 +258,7 @@ class TuyaDevice(LightEntity):
|
|||||||
|
|
||||||
def turn_on(self, **kwargs):
|
def turn_on(self, **kwargs):
|
||||||
"""Turn on or control the light."""
|
"""Turn on or control the light."""
|
||||||
log.debug("Turning on, state: " + str(self._device.cached_status()))
|
_LOGGER.debug("Turning on, state: %s", self._device.cached_status())
|
||||||
if not self._device.cached_status():
|
if not self._device.cached_status():
|
||||||
self._device.set_status(True, self._bulb_id)
|
self._device.set_status(True, self._bulb_id)
|
||||||
if ATTR_BRIGHTNESS in kwargs:
|
if ATTR_BRIGHTNESS in kwargs:
|
||||||
@@ -305,7 +269,11 @@ class TuyaDevice(LightEntity):
|
|||||||
if ATTR_HS_COLOR in kwargs:
|
if ATTR_HS_COLOR in kwargs:
|
||||||
raise ValueError(" TODO implement RGB from HS")
|
raise ValueError(" TODO implement RGB from HS")
|
||||||
if ATTR_COLOR_TEMP in kwargs:
|
if ATTR_COLOR_TEMP in kwargs:
|
||||||
color_temp = int(255 - (255 / (MAX_MIRED - MIN_MIRED)) * (int(kwargs[ATTR_COLOR_TEMP]) - MIN_MIRED))
|
color_temp = int(
|
||||||
|
255
|
||||||
|
- (255 / (MAX_MIRED - MIN_MIRED))
|
||||||
|
* (int(kwargs[ATTR_COLOR_TEMP]) - MIN_MIRED)
|
||||||
|
)
|
||||||
self._device.set_color_temp(color_temp)
|
self._device.set_color_temp(color_temp)
|
||||||
|
|
||||||
def turn_off(self, **kwargs):
|
def turn_off(self, **kwargs):
|
||||||
|
@@ -25,49 +25,39 @@ switch:
|
|||||||
id: 7
|
id: 7
|
||||||
"""
|
"""
|
||||||
import logging
|
import logging
|
||||||
|
from time import time, sleep
|
||||||
|
from threading import Lock
|
||||||
|
|
||||||
import voluptuous as vol
|
import voluptuous as vol
|
||||||
|
|
||||||
from homeassistant.components.switch import SwitchEntity, PLATFORM_SCHEMA
|
from homeassistant.components.switch import SwitchEntity, PLATFORM_SCHEMA
|
||||||
from homeassistant.const import (
|
from homeassistant.const import (
|
||||||
CONF_HOST,
|
|
||||||
CONF_ID,
|
CONF_ID,
|
||||||
CONF_ENTITIES,
|
|
||||||
CONF_SWITCHES,
|
CONF_SWITCHES,
|
||||||
CONF_DEVICE_ID,
|
|
||||||
CONF_FRIENDLY_NAME,
|
CONF_FRIENDLY_NAME,
|
||||||
CONF_ICON,
|
|
||||||
CONF_NAME,
|
CONF_NAME,
|
||||||
CONF_PLATFORM,
|
|
||||||
)
|
)
|
||||||
from homeassistant.config_entries import SOURCE_IMPORT
|
|
||||||
import homeassistant.helpers.config_validation as cv
|
import homeassistant.helpers.config_validation as cv
|
||||||
from time import time, sleep
|
|
||||||
from threading import Lock
|
|
||||||
|
|
||||||
from . import pytuya
|
from . import BASE_PLATFORM_SCHEMA, prepare_setup_entities, import_from_yaml
|
||||||
from .const import (
|
from .const import (
|
||||||
ATTR_CURRENT,
|
ATTR_CURRENT,
|
||||||
ATTR_CURRENT_CONSUMPTION,
|
ATTR_CURRENT_CONSUMPTION,
|
||||||
ATTR_VOLTAGE,
|
ATTR_VOLTAGE,
|
||||||
CONF_LOCAL_KEY,
|
|
||||||
CONF_PROTOCOL_VERSION,
|
|
||||||
CONF_CURRENT,
|
CONF_CURRENT,
|
||||||
CONF_CURRENT_CONSUMPTION,
|
CONF_CURRENT_CONSUMPTION,
|
||||||
CONF_VOLTAGE,
|
CONF_VOLTAGE,
|
||||||
DOMAIN,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
REQUIREMENTS = ["pytuya==7.0.9"]
|
|
||||||
|
|
||||||
DEFAULT_ID = "1"
|
DEFAULT_ID = "1"
|
||||||
DEFAULT_PROTOCOL_VERSION = 3.3
|
|
||||||
|
|
||||||
|
# TODO: This will eventully merge with flow_schema
|
||||||
SWITCH_SCHEMA = vol.Schema(
|
SWITCH_SCHEMA = vol.Schema(
|
||||||
{
|
{
|
||||||
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
vol.Optional(CONF_ID, default=DEFAULT_ID): cv.string,
|
||||||
vol.Required(CONF_NAME): cv.string,
|
vol.Optional(CONF_NAME): cv.string, # Deprecated: not used
|
||||||
vol.Required(CONF_FRIENDLY_NAME): cv.string,
|
vol.Required(CONF_FRIENDLY_NAME): cv.string,
|
||||||
vol.Optional(CONF_CURRENT, default="-1"): cv.string,
|
vol.Optional(CONF_CURRENT, default="-1"): cv.string,
|
||||||
vol.Optional(CONF_CURRENT_CONSUMPTION, default="-1"): cv.string,
|
vol.Optional(CONF_CURRENT_CONSUMPTION, default="-1"): cv.string,
|
||||||
@@ -75,18 +65,8 @@ SWITCH_SCHEMA = vol.Schema(
|
|||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(BASE_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, default="-1"): cv.string,
|
||||||
vol.Optional(CONF_CURRENT_CONSUMPTION, default="-1"): cv.string,
|
vol.Optional(CONF_CURRENT_CONSUMPTION, default="-1"): cv.string,
|
||||||
vol.Optional(CONF_VOLTAGE, default="-1"): cv.string,
|
vol.Optional(CONF_VOLTAGE, default="-1"): cv.string,
|
||||||
@@ -95,36 +75,26 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
DPS_FIELDS = [
|
def flow_schema(dps):
|
||||||
vol.Optional(CONF_CURRENT),
|
"""Return schema used in config flow."""
|
||||||
vol.Optional(CONF_CURRENT_CONSUMPTION),
|
return {
|
||||||
vol.Optional(CONF_VOLTAGE),
|
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):
|
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."""
|
||||||
switches_to_setup = [
|
device, entities_to_setup = prepare_setup_entities(config_entry, "switch")
|
||||||
entity
|
if not entities_to_setup:
|
||||||
for entity in config_entry.data[CONF_ENTITIES]
|
|
||||||
if entity[CONF_PLATFORM] == "switch"
|
|
||||||
]
|
|
||||||
if not switches_to_setup:
|
|
||||||
return
|
return
|
||||||
|
|
||||||
switches = []
|
switches = []
|
||||||
pytuyadevice = pytuya.OutletDevice(
|
for device_config in entities_to_setup:
|
||||||
config_entry.data[CONF_DEVICE_ID],
|
|
||||||
config_entry.data[CONF_HOST],
|
|
||||||
config_entry.data[CONF_LOCAL_KEY],
|
|
||||||
)
|
|
||||||
pytuyadevice.set_version(float(config_entry.data[CONF_PROTOCOL_VERSION]))
|
|
||||||
pytuyadevice.set_dpsUsed({})
|
|
||||||
|
|
||||||
for device_config in switches_to_setup:
|
|
||||||
switches.append(
|
switches.append(
|
||||||
TuyaDevice(
|
TuyaDevice(
|
||||||
TuyaCache(pytuyadevice),
|
TuyaCache(device),
|
||||||
device_config[CONF_FRIENDLY_NAME],
|
device_config[CONF_FRIENDLY_NAME],
|
||||||
device_config[CONF_ID],
|
device_config[CONF_ID],
|
||||||
device_config.get(CONF_CURRENT),
|
device_config.get(CONF_CURRENT),
|
||||||
@@ -138,14 +108,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
|
|||||||
|
|
||||||
def setup_platform(hass, config, add_devices, discovery_info=None):
|
def setup_platform(hass, config, add_devices, discovery_info=None):
|
||||||
"""Set up of the Tuya switch."""
|
"""Set up of the Tuya switch."""
|
||||||
config[CONF_PLATFORM] = "switch"
|
return import_from_yaml(hass, config, "switch")
|
||||||
hass.async_create_task(
|
|
||||||
hass.config_entries.flow.async_init(
|
|
||||||
DOMAIN, context={"source": SOURCE_IMPORT}, data=config
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
class TuyaCache:
|
class TuyaCache:
|
||||||
|
Reference in New Issue
Block a user