Add support for config flows for switches
This commit is contained in:
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
*~
|
||||||
|
__pycache__
|
@@ -1 +1,30 @@
|
|||||||
"""The Tuya local integration."""
|
"""The LocalTuya integration integration."""
|
||||||
|
import asyncio
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant.config_entries import ConfigEntry
|
||||||
|
from homeassistant.core import HomeAssistant
|
||||||
|
|
||||||
|
from .const import CONF_DEVICE_TYPE, DOMAIN, DEVICE_TYPE_POWER_OUTLET
|
||||||
|
|
||||||
|
|
||||||
|
async def async_setup(hass: HomeAssistant, config: dict):
|
||||||
|
"""Set up the LocalTuya integration component."""
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||||
|
"""Set up LocalTuya integration from a config entry."""
|
||||||
|
if entry.data[CONF_DEVICE_TYPE] == DEVICE_TYPE_POWER_OUTLET:
|
||||||
|
hass.async_create_task(
|
||||||
|
hass.config_entries.async_forward_entry_setup(entry, "switch")
|
||||||
|
)
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry):
|
||||||
|
"""Unload a config entry."""
|
||||||
|
# Nothing is stored and no persistent connections exist, so nothing to do
|
||||||
|
return True
|
||||||
|
140
custom_components/localtuya/config_flow.py
Normal file
140
custom_components/localtuya/config_flow.py
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
"""Config flow for LocalTuya integration integration."""
|
||||||
|
import logging
|
||||||
|
|
||||||
|
import voluptuous as vol
|
||||||
|
|
||||||
|
from homeassistant import config_entries, core, exceptions
|
||||||
|
from homeassistant.const import (
|
||||||
|
CONF_SWITCHES,
|
||||||
|
CONF_ID,
|
||||||
|
CONF_HOST,
|
||||||
|
CONF_DEVICE_ID,
|
||||||
|
CONF_NAME,
|
||||||
|
CONF_FRIENDLY_NAME,
|
||||||
|
)
|
||||||
|
import homeassistant.helpers.config_validation as cv
|
||||||
|
|
||||||
|
from . import pytuya
|
||||||
|
from .const import ( # pylint: disable=unused-import
|
||||||
|
CONF_DEVICE_TYPE,
|
||||||
|
CONF_LOCAL_KEY,
|
||||||
|
CONF_PROTOCOL_VERSION,
|
||||||
|
CONF_CURRENT,
|
||||||
|
CONF_CURRENT_CONSUMPTION,
|
||||||
|
CONF_VOLTAGE,
|
||||||
|
DOMAIN,
|
||||||
|
DEVICE_TYPE_POWER_OUTLET,
|
||||||
|
)
|
||||||
|
|
||||||
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
ADD_ANOTHER_SWITCH = "add_another_switch"
|
||||||
|
|
||||||
|
USER_SCHEMA = vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required(CONF_NAME): str,
|
||||||
|
vol.Required(CONF_HOST): str,
|
||||||
|
vol.Required(CONF_DEVICE_ID): str,
|
||||||
|
vol.Required(CONF_LOCAL_KEY): str,
|
||||||
|
vol.Required(CONF_PROTOCOL_VERSION, default="3.3"): vol.In(["3.1", "3.3"]),
|
||||||
|
vol.Required(CONF_DEVICE_TYPE, default=DEVICE_TYPE_POWER_OUTLET): vol.In(
|
||||||
|
[DEVICE_TYPE_POWER_OUTLET]
|
||||||
|
),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
POWER_OUTLET_SCHEMA = vol.Schema(
|
||||||
|
{
|
||||||
|
vol.Required(CONF_ID, default=1): int,
|
||||||
|
vol.Required(CONF_NAME): str,
|
||||||
|
vol.Required(CONF_FRIENDLY_NAME): str,
|
||||||
|
vol.Required(CONF_CURRENT, default=18): int,
|
||||||
|
vol.Required(CONF_CURRENT_CONSUMPTION, default=19): int,
|
||||||
|
vol.Required(CONF_VOLTAGE, default=20): int,
|
||||||
|
vol.Required(ADD_ANOTHER_SWITCH, default=False): bool,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def validate_input(hass: core.HomeAssistant, data):
|
||||||
|
"""Validate the user input allows us to connect."""
|
||||||
|
pytuyadevice = pytuya.OutletDevice(
|
||||||
|
data[CONF_DEVICE_ID], data[CONF_HOST], data[CONF_LOCAL_KEY]
|
||||||
|
)
|
||||||
|
pytuyadevice.set_version(float(data[CONF_PROTOCOL_VERSION]))
|
||||||
|
pytuyadevice.set_dpsUsed({"1": None})
|
||||||
|
try:
|
||||||
|
await hass.async_add_executor_job(pytuyadevice.status)
|
||||||
|
except ConnectionRefusedError:
|
||||||
|
raise CannotConnect
|
||||||
|
except ValueError:
|
||||||
|
raise InvalidAuth
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
class LocaltuyaConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
|
||||||
|
"""Handle a config flow for LocalTuya integration."""
|
||||||
|
|
||||||
|
VERSION = 1
|
||||||
|
CONNECTION_CLASS = config_entries.CONN_CLASS_LOCAL_POLL
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
"""Initialize a new LocaltuyaConfigFlow."""
|
||||||
|
self.basic_info = None
|
||||||
|
self.switches = []
|
||||||
|
|
||||||
|
async def async_step_user(self, user_input=None):
|
||||||
|
"""Handle the initial step."""
|
||||||
|
errors = {}
|
||||||
|
if user_input is not None:
|
||||||
|
await self.async_set_unique_id(user_input[CONF_DEVICE_ID])
|
||||||
|
self._abort_if_unique_id_configured()
|
||||||
|
|
||||||
|
try:
|
||||||
|
self.basic_info = await validate_input(self.hass, user_input)
|
||||||
|
if self.basic_info[CONF_DEVICE_TYPE] == "Power Outlet":
|
||||||
|
return await self.async_step_power_outlet()
|
||||||
|
|
||||||
|
return self.async_abort(reason="unsupported_device_type")
|
||||||
|
except CannotConnect:
|
||||||
|
errors["base"] = "cannot_connect"
|
||||||
|
except InvalidAuth:
|
||||||
|
errors["base"] = "invalid_auth"
|
||||||
|
except Exception: # pylint: disable=broad-except
|
||||||
|
_LOGGER.exception("Unexpected exception")
|
||||||
|
errors["base"] = "unknown"
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="user", data_schema=USER_SCHEMA, errors=errors
|
||||||
|
)
|
||||||
|
|
||||||
|
async def async_step_power_outlet(self, user_input=None):
|
||||||
|
"""Handle the initial step."""
|
||||||
|
errors = {}
|
||||||
|
if user_input is not None:
|
||||||
|
already_configured = any(
|
||||||
|
switch[CONF_ID] == user_input[CONF_ID] for switch in self.switches
|
||||||
|
)
|
||||||
|
if not already_configured:
|
||||||
|
add_another_switch = user_input.pop(ADD_ANOTHER_SWITCH)
|
||||||
|
self.switches.append(user_input)
|
||||||
|
if not add_another_switch:
|
||||||
|
config = {**self.basic_info, CONF_SWITCHES: self.switches}
|
||||||
|
return self.async_create_entry(title=config[CONF_NAME], data=config)
|
||||||
|
else:
|
||||||
|
errors["base"] = "switch_already_configured"
|
||||||
|
|
||||||
|
return self.async_show_form(
|
||||||
|
step_id="power_outlet",
|
||||||
|
data_schema=POWER_OUTLET_SCHEMA,
|
||||||
|
errors=errors,
|
||||||
|
description_placeholders={"number": len(self.switches) + 1},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class CannotConnect(exceptions.HomeAssistantError):
|
||||||
|
"""Error to indicate we cannot connect."""
|
||||||
|
|
||||||
|
|
||||||
|
class InvalidAuth(exceptions.HomeAssistantError):
|
||||||
|
"""Error to indicate there is invalid auth."""
|
12
custom_components/localtuya/const.py
Normal file
12
custom_components/localtuya/const.py
Normal file
@@ -0,0 +1,12 @@
|
|||||||
|
"""Constants for localtuya integration."""
|
||||||
|
|
||||||
|
CONF_DEVICE_TYPE = "device_type"
|
||||||
|
CONF_LOCAL_KEY = "local_key"
|
||||||
|
CONF_PROTOCOL_VERSION = "protocol_version"
|
||||||
|
CONF_CURRENT = "current"
|
||||||
|
CONF_CURRENT_CONSUMPTION = "current_consumption"
|
||||||
|
CONF_VOLTAGE = "voltage"
|
||||||
|
|
||||||
|
DOMAIN = "localtuya"
|
||||||
|
|
||||||
|
DEVICE_TYPE_POWER_OUTLET = "Power Outlet"
|
@@ -1,8 +1,11 @@
|
|||||||
{
|
{
|
||||||
"domain": "localtuya",
|
"domain": "localtuya",
|
||||||
"name": "LocalTuya integration",
|
"name": "LocalTuya integration",
|
||||||
"documentation": "https://github.com/rospogrigio/localtuya-homeassistant/",
|
"documentation": "https://github.com/rospogrigio/localtuya-homeassistant/",
|
||||||
"dependencies": [],
|
"dependencies": [],
|
||||||
"codeowners": ["@rospogrigio"],
|
"codeowners": [
|
||||||
"requirements": ["pycryptodome==3.9.8"]
|
"@rospogrigio"
|
||||||
|
],
|
||||||
|
"requirements": ["pycryptodome==3.9.8"],
|
||||||
|
"config_flow": true
|
||||||
}
|
}
|
42
custom_components/localtuya/strings.json
Normal file
42
custom_components/localtuya/strings.json
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "Device has already been configured.",
|
||||||
|
"unsupported_device_type": "Unsupported device type!"
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"cannot_connect": "Cannot connect to device. Verify that address is correct.",
|
||||||
|
"invalid_auth": "Failed to authenticate with device. Verify that device id and local key are correct.",
|
||||||
|
"unknown": "An unknown error occurred. See log for details.",
|
||||||
|
"switch_already_configured": "Switch with this ID has already been configured."
|
||||||
|
},
|
||||||
|
"step": {
|
||||||
|
"user": {
|
||||||
|
"title": "Add Tuya device",
|
||||||
|
"description": "Fill in the basic details and pick device type. The name entered here will be used to identify the integration itself (as seen in the `Integrations` page). You will name each sub-device in the following steps.",
|
||||||
|
"data": {
|
||||||
|
"name": "Name",
|
||||||
|
"host": "Host",
|
||||||
|
"device_id": "Device ID",
|
||||||
|
"local_key": "Local key",
|
||||||
|
"protocol_version": "Protocol Version",
|
||||||
|
"device_type": "Device type"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"power_outlet": {
|
||||||
|
"title": "Add subswitch",
|
||||||
|
"description": "You are about to add subswitch number `{number}`. If you want to add another, tick `Add another switch` before continuing.",
|
||||||
|
"data": {
|
||||||
|
"id": "ID",
|
||||||
|
"name": "Name",
|
||||||
|
"friendly_name": "Friendly name",
|
||||||
|
"current": "Current",
|
||||||
|
"current_consumption": "Current Consumption",
|
||||||
|
"voltage": "Voltage",
|
||||||
|
"add_another_switch": "Add another switch"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"title": "LocalTuya"
|
||||||
|
}
|
@@ -28,22 +28,18 @@ import logging
|
|||||||
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 (CONF_HOST, CONF_ID, CONF_SWITCHES, CONF_FRIENDLY_NAME, CONF_ICON, CONF_NAME)
|
from homeassistant.const import (CONF_HOST, CONF_ID, CONF_SWITCHES, CONF_DEVICE_ID, CONF_FRIENDLY_NAME, CONF_ICON, CONF_NAME)
|
||||||
import homeassistant.helpers.config_validation as cv
|
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
|
||||||
|
|
||||||
|
from . import pytuya
|
||||||
|
from .const import CONF_LOCAL_KEY, CONF_PROTOCOL_VERSION, CONF_CURRENT, CONF_CURRENT_CONSUMPTION, CONF_VOLTAGE
|
||||||
|
|
||||||
_LOGGER = logging.getLogger(__name__)
|
_LOGGER = logging.getLogger(__name__)
|
||||||
|
|
||||||
REQUIREMENTS = ['pytuya==7.0.9']
|
REQUIREMENTS = ['pytuya==7.0.9']
|
||||||
|
|
||||||
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'
|
|
||||||
|
|
||||||
DEFAULT_ID = '1'
|
DEFAULT_ID = '1'
|
||||||
DEFAULT_PROTOCOL_VERSION = 3.3
|
DEFAULT_PROTOCOL_VERSION = 3.3
|
||||||
|
|
||||||
@@ -77,6 +73,43 @@ PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
|
|||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
async def async_setup_entry(hass, config_entry, async_add_entities):
|
||||||
|
"""Setup a Tuya switch based on a config entry."""
|
||||||
|
switches = []
|
||||||
|
pytuyadevice = pytuya.OutletDevice(
|
||||||
|
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]))
|
||||||
|
dps = {}
|
||||||
|
|
||||||
|
for device_config in config_entry.data[CONF_SWITCHES]:
|
||||||
|
dps[str(device_config[CONF_ID])] = None
|
||||||
|
if device_config[CONF_CURRENT] != 0:
|
||||||
|
dps[str(device_config[CONF_CURRENT])] = None
|
||||||
|
if device_config[CONF_CURRENT_CONSUMPTION] != 0:
|
||||||
|
dps[str(device_config[CONF_CURRENT_CONSUMPTION])] = None
|
||||||
|
if device_config[CONF_VOLTAGE] != 0:
|
||||||
|
dps[str(device_config[CONF_VOLTAGE])] = None
|
||||||
|
|
||||||
|
switches.append(
|
||||||
|
TuyaDevice(
|
||||||
|
TuyaCache(pytuyadevice),
|
||||||
|
device_config[CONF_NAME],
|
||||||
|
device_config[CONF_FRIENDLY_NAME],
|
||||||
|
None, # Icon
|
||||||
|
str(device_config[CONF_ID]),
|
||||||
|
str(device_config[CONF_CURRENT]),
|
||||||
|
str(device_config[CONF_CURRENT_CONSUMPTION]),
|
||||||
|
str(device_config[CONF_VOLTAGE])
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
pytuyadevice.set_dpsUsed(dps)
|
||||||
|
|
||||||
|
async_add_entities(switches, 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
|
from . import pytuya
|
||||||
@@ -199,6 +232,7 @@ class TuyaCache:
|
|||||||
finally:
|
finally:
|
||||||
self._lock.release()
|
self._lock.release()
|
||||||
|
|
||||||
|
|
||||||
class TuyaDevice(SwitchEntity):
|
class TuyaDevice(SwitchEntity):
|
||||||
"""Representation of a Tuya switch."""
|
"""Representation of a Tuya switch."""
|
||||||
|
|
||||||
@@ -212,8 +246,8 @@ class TuyaDevice(SwitchEntity):
|
|||||||
self._attr_current = attr_current
|
self._attr_current = attr_current
|
||||||
self._attr_consumption = attr_consumption
|
self._attr_consumption = attr_consumption
|
||||||
self._attr_voltage = attr_voltage
|
self._attr_voltage = attr_voltage
|
||||||
self._status = self._device.status()
|
self._status = None
|
||||||
self._state = self._status['dps'][self._switch_id]
|
self._state = None
|
||||||
print('Initialized tuya switch [{}] with switch status [{}] and state [{}]'.format(self._name, self._status, self._state))
|
print('Initialized tuya switch [{}] with switch status [{}] and state [{}]'.format(self._name, self._status, self._state))
|
||||||
|
|
||||||
@property
|
@property
|
||||||
|
42
custom_components/localtuya/translations/en.json
Normal file
42
custom_components/localtuya/translations/en.json
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
{
|
||||||
|
"config": {
|
||||||
|
"abort": {
|
||||||
|
"already_configured": "Device has already been configured.",
|
||||||
|
"unsupported_device_type": "Unsupported device type!"
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"cannot_connect": "Cannot connect to device. Verify that address is correct.",
|
||||||
|
"invalid_auth": "Failed to authenticate with device. Verify that device id and local key are correct.",
|
||||||
|
"unknown": "An unknown error occurred. See log for details.",
|
||||||
|
"switch_already_configured": "Switch with this ID has already been configured."
|
||||||
|
},
|
||||||
|
"step": {
|
||||||
|
"user": {
|
||||||
|
"title": "Add Tuya device",
|
||||||
|
"description": "Fill in the basic details and pick device type. The name entered here will be used to identify the integration itself (as seen in the `Integrations` page). You will name each sub-device in the following steps.",
|
||||||
|
"data": {
|
||||||
|
"name": "Name",
|
||||||
|
"host": "Host",
|
||||||
|
"device_id": "Device ID",
|
||||||
|
"local_key": "Local key",
|
||||||
|
"protocol_version": "Protocol Version",
|
||||||
|
"device_type": "Device type"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"power_outlet": {
|
||||||
|
"title": "Add subswitch",
|
||||||
|
"description": "You are about to add subswitch number `{number}`. If you want to add another, tick `Add another switch` before continuing.",
|
||||||
|
"data": {
|
||||||
|
"id": "ID",
|
||||||
|
"name": "Name",
|
||||||
|
"friendly_name": "Friendly name",
|
||||||
|
"current": "Current",
|
||||||
|
"current_consumption": "Current Consumption",
|
||||||
|
"voltage": "Voltage",
|
||||||
|
"add_another_switch": "Add another switch"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"title": "LocalTuya"
|
||||||
|
}
|
Reference in New Issue
Block a user