Skip to content

Commit

Permalink
Reformat
Browse files Browse the repository at this point in the history
- Bump HA to 2023.05
- Bump Python worksflow 3.10
- Reformat all codes
  • Loading branch information
xZetsubou authored Aug 13, 2023
1 parent 04275d8 commit 7fa4365
Show file tree
Hide file tree
Showing 9 changed files with 128 additions and 72 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/tox.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ jobs:
platform:
- ubuntu-latest
python-version:
- 3.9
- '3.10'
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
Expand Down
17 changes: 8 additions & 9 deletions custom_components/localtuya/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,21 +220,20 @@ async def async_migrate_entry(hass, config_entry: ConfigEntry):
hass.config_entries.async_update_entry(stored_entries[0], data=new_data)
await hass.config_entries.async_remove(config_entry.entry_id)
if config_entry.version == 2:
""" Switch config flow to selectors convert DP IDs from int to str `require HA 2022.4 ` """
# Switch config flow to selectors convert DP IDs from int to str require HA 2022.4.
_LOGGER.debug("Migrating config entry from version %s", config_entry.version)
if config_entry.entry_id == stored_entries[0].entry_id:
new_data = stored_entries[0].data.copy()
for device in new_data[CONF_DEVICES]:
i = 0
if new_data[CONF_DEVICES][device][CONF_ENTITIES] is not None:
for _ent in new_data[CONF_DEVICES][device][CONF_ENTITIES]:
ent_items = {}
for k, v in _ent.items():
ent_items[k] = str(v) if type(v) == type(1) else v
new_data[CONF_DEVICES][device][CONF_ENTITIES][i].update(ent_items)
i = i + 1
for _ent in new_data[CONF_DEVICES][device][CONF_ENTITIES]:
ent_items = {}
for k, v in _ent.items():
ent_items[k] = str(v) if isinstance(v, int) else v
new_data[CONF_DEVICES][device][CONF_ENTITIES][i].update(ent_items)
i = i + 1
config_entry.version = new_version
hass.config_entries.async_update_entry(config_entry, data=new_data)
hass.config_entries.async_update_entry(config_entry, data=new_data)

_LOGGER.info(
"Entry %s successfully migrated to version %s.",
Expand Down
11 changes: 9 additions & 2 deletions custom_components/localtuya/button.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,14 +23,21 @@ def flow_schema(dps):
class LocaltuyaButton(LocalTuyaEntity, ButtonEntity):
"""Representation of a Tuya button."""

def __init__(self,device,config_entry,buttonid,**kwargs,):
def __init__(
self,
device,
config_entry,
buttonid,
**kwargs,
):
"""Initialize the Tuya button."""
super().__init__(device, config_entry, buttonid, _LOGGER, **kwargs)
self._state = None
_LOGGER.debug("Initialized button [%s]", self.name)

async def async_press(self):
"""Press the button"""
"""Press the button."""
await self._device.set_dp(True, self._dp_id)


async_setup_entry = partial(async_setup_entry, DOMAIN, LocaltuyaButton, flow_schema)
4 changes: 3 additions & 1 deletion custom_components/localtuya/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,9 @@ def flow_schema(dps):
vol.Optional(CONF_HVAC_MODE_DP): _col_to_select(dps, is_dps=True),
vol.Optional(CONF_HVAC_MODE_SET): _col_to_select(list(HVAC_MODE_SETS.keys())),
vol.Optional(CONF_HVAC_ACTION_DP): _col_to_select(dps, is_dps=True),
vol.Optional(CONF_HVAC_ACTION_SET): _col_to_select(list(HVAC_ACTION_SETS.keys())),
vol.Optional(CONF_HVAC_ACTION_SET): _col_to_select(
list(HVAC_ACTION_SETS.keys())
),
vol.Optional(CONF_ECO_DP): _col_to_select(dps, is_dps=True),
vol.Optional(CONF_ECO_VALUE): str,
vol.Optional(CONF_PRESET_DP): _col_to_select(dps, is_dps=True),
Expand Down
75 changes: 54 additions & 21 deletions custom_components/localtuya/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,16 @@


import homeassistant.helpers.config_validation as cv
import homeassistant.helpers.entity_registry as er

# import homeassistant.helpers.entity_registry as er # Disabled it because no need to delete registry.
import voluptuous as vol
from homeassistant import config_entries, core, exceptions
from homeassistant.helpers.selector import SelectSelector, SelectSelectorConfig, SelectSelectorMode, SelectOptionDict
from homeassistant.helpers.selector import (
SelectSelector,
SelectSelectorConfig,
SelectSelectorMode,
SelectOptionDict,
)
from homeassistant.const import (
CONF_CLIENT_ID,
CONF_CLIENT_SECRET,
Expand Down Expand Up @@ -59,20 +65,33 @@

_LOGGER = logging.getLogger(__name__)

def _col_to_select(opt_list: dict, multi_select = False, is_dps = False):

def _col_to_select(opt_list: dict, multi_select=False, is_dps=False):
"""Convert collections to SelectSelectorConfig."""
if type(opt_list) == dict:
return SelectSelector(SelectSelectorConfig(
options=[SelectOptionDict(value=str(k), label=l) for l, k in opt_list.items()],
mode=SelectSelectorMode.DROPDOWN,
))
return SelectSelector(
SelectSelectorConfig(
options=[
SelectOptionDict(value=str(v), label=k) for k, v in opt_list.items()
],
mode=SelectSelectorMode.DROPDOWN,
)
)
elif type(opt_list) == list:
# value used the same method as func available_dps_string, no spaces values.
return SelectSelector(SelectSelectorConfig(
options=[SelectOptionDict(value=str(l).split(' ')[0] if is_dps == True else str(l)
, label=str(l)) for l in opt_list],
mode=SelectSelectorMode.DROPDOWN, multiple = True if multi_select == True else False,
))
# value used the same method as func available_dps_string, no spaces values.
return SelectSelector(
SelectSelectorConfig(
options=[
SelectOptionDict(
value=str(kv).split(" ")[0] if is_dps else str(kv),
label=str(kv),
)
for kv in opt_list
],
mode=SelectSelectorMode.DROPDOWN,
multiple=True if multi_select else False,
)
)


ENTRIES_VERSION = 3
Expand All @@ -81,7 +100,7 @@ def _col_to_select(opt_list: dict, multi_select = False, is_dps = False):
NO_ADDITIONAL_ENTITIES = "no_additional_entities"
SELECTED_DEVICE = "selected_device"

CUSTOM_DEVICE = {"Add custom device" : "..."}
CUSTOM_DEVICE = {"Add custom device": "..."}

CONF_ACTIONS = {
CONF_ADD_DEVICE: "Add a new device",
Expand All @@ -97,7 +116,9 @@ def _col_to_select(opt_list: dict, multi_select = False, is_dps = False):

CLOUD_SETUP_SCHEMA = vol.Schema(
{
vol.Required(CONF_REGION, default="eu"): _col_to_select(["eu", "us", "cn", "in"]),
vol.Required(CONF_REGION, default="eu"): _col_to_select(
["eu", "us", "cn", "in"]
),
vol.Optional(CONF_CLIENT_ID): cv.string,
vol.Optional(CONF_CLIENT_SECRET): cv.string,
vol.Optional(CONF_USER_ID): cv.string,
Expand Down Expand Up @@ -127,6 +148,7 @@ def _col_to_select(opt_list: dict, multi_select = False, is_dps = False):
{vol.Required(PLATFORM_TO_ADD, default="switch"): _col_to_select(PLATFORMS)}
)


def devices_schema(discovered_devices, cloud_devices_list, add_custom_device=True):
"""Create schema for devices step."""
devices = {}
Expand All @@ -145,7 +167,13 @@ def devices_schema(discovered_devices, cloud_devices_list, add_custom_device=Tru
# for ent in entries
# }
# )
return vol.Schema({vol.Required(SELECTED_DEVICE, default=list(devices.values())[0]): _col_to_select(devices)})
return vol.Schema(
{
vol.Required(
SELECTED_DEVICE, default=list(devices.values())[0]
): _col_to_select(devices)
}
)


def options_schema(entities):
Expand All @@ -167,7 +195,8 @@ def options_schema(entities):
vol.Optional(CONF_RESET_DPIDS): cv.string,
vol.Required(
CONF_ENTITIES, description={"suggested_value": entity_names}
): cv.multi_select(entity_names),# _col_to_select(entity_names, multi_select=True)
): cv.multi_select(entity_names),
# _col_to_select(entity_names, multi_select=True)
vol.Required(CONF_ENABLE_ADD_ENTITIES, default=False): bool,
}
)
Expand Down Expand Up @@ -219,20 +248,24 @@ def platform_schema(platform, dps_strings, allow_id=True, yaml=False):
if allow_id:
schema[vol.Required(CONF_ID)] = _col_to_select(dps_strings, is_dps=True)
schema[vol.Required(CONF_FRIENDLY_NAME)] = str
schema[vol.Required(CONF_CATEGORY_ENTITY, default=str(default_category(platform)))] = _col_to_select(ENTITY_CATEGORY)
schema[
vol.Required(CONF_CATEGORY_ENTITY, default=str(default_category(platform)))
] = _col_to_select(ENTITY_CATEGORY)
return vol.Schema(schema).extend(flow_schema(platform, dps_strings))


def default_category(_platform):
"""Auto Select default category depends on the platform"""
"""Auto Select default category depends on the platform."""
if any(_platform in i for i in DEFAULT_CATEGORIES["CONTROL"]):
return str(None)
elif any(_platform in i for i in DEFAULT_CATEGORIES["CONFIG"]):
return EntityCategory.CONFIG
elif any(_platform in i for i in DEFAULT_CATEGORIES["DIAGNOSTIC"]):
return EntityCategory.DIAGNOSTIC
return EntityCategory.DIAGNOSTIC
else:
return str(None)


def flow_schema(platform, dps_strings):
"""Return flow schema for a specific platform."""
integration_module = ".".join(__name__.split(".")[:-1])
Expand Down Expand Up @@ -791,7 +824,7 @@ async def async_step_configure_entity(self, user_input=None):
# finished editing device. Let's store the new config entry....
dev_id = self.device_data[CONF_DEVICE_ID]
new_data = self.config_entry.data.copy()
entry_id = self.config_entry.entry_id
# entry_id = self.config_entry.entry_id
# removing entities from registry (they will be recreated)
# ent_reg = er.async_get(self.hass)
# reg_entities = {
Expand Down
13 changes: 6 additions & 7 deletions custom_components/localtuya/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
"switch",
"vacuum",
]

TUYA_DEVICES = "tuya_devices"

ATTR_CURRENT = "current"
Expand Down Expand Up @@ -142,14 +141,14 @@

# Categories
ENTITY_CATEGORY = {
"Controls" : None,
"Configuration" : EntityCategory.CONFIG,
"Diagnostic" : EntityCategory.DIAGNOSTIC
"Controls": None,
"Configuration": EntityCategory.CONFIG,
"Diagnostic": EntityCategory.DIAGNOSTIC,
}

# Default Categories
DEFAULT_CATEGORIES = {
"CONTROL" : ['switch', 'climate','fan','vacuum','light'],
"CONFIG" : ['select','number','button'],
"DIAGNOSTIC" : ['sensor','binary_sensor']
"CONTROL": ["switch", "climate", "fan", "vacuum", "light"],
"CONFIG": ["select", "number", "button"],
"DIAGNOSTIC": ["sensor", "binary_sensor"],
}
Loading

0 comments on commit 7fa4365

Please sign in to comment.