Home connect use consts (#46659)

* Use more consts

* black

* re-black with black, version 20.8b1
This commit is contained in:
badguy99 2021-02-17 08:44:37 +00:00 committed by GitHub
parent ddf1f88b65
commit 971e27dd80
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 102 additions and 70 deletions

View File

@ -7,11 +7,27 @@ import homeconnect
from homeconnect.api import HomeConnectError from homeconnect.api import HomeConnectError
from homeassistant import config_entries, core from homeassistant import config_entries, core
from homeassistant.const import DEVICE_CLASS_TIMESTAMP, PERCENTAGE, TIME_SECONDS from homeassistant.const import (
ATTR_DEVICE_CLASS,
ATTR_ICON,
CONF_DEVICE,
CONF_ENTITIES,
DEVICE_CLASS_TIMESTAMP,
PERCENTAGE,
TIME_SECONDS,
)
from homeassistant.helpers import config_entry_oauth2_flow from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.helpers.dispatcher import dispatcher_send from homeassistant.helpers.dispatcher import dispatcher_send
from .const import ( from .const import (
ATTR_AMBIENT,
ATTR_DESC,
ATTR_DEVICE,
ATTR_KEY,
ATTR_SENSOR_TYPE,
ATTR_SIGN,
ATTR_UNIT,
ATTR_VALUE,
BSH_ACTIVE_PROGRAM, BSH_ACTIVE_PROGRAM,
BSH_OPERATION_STATE, BSH_OPERATION_STATE,
BSH_POWER_OFF, BSH_POWER_OFF,
@ -72,7 +88,9 @@ class ConfigEntryAuth(homeconnect.HomeConnectAPI):
else: else:
_LOGGER.warning("Appliance type %s not implemented", app.type) _LOGGER.warning("Appliance type %s not implemented", app.type)
continue continue
devices.append({"device": device, "entities": device.get_entity_info()}) devices.append(
{CONF_DEVICE: device, CONF_ENTITIES: device.get_entity_info()}
)
self.devices = devices self.devices = devices
return devices return devices
@ -104,8 +122,10 @@ class HomeConnectDevice:
except (HomeConnectError, ValueError): except (HomeConnectError, ValueError):
_LOGGER.debug("Unable to fetch active programs. Probably offline") _LOGGER.debug("Unable to fetch active programs. Probably offline")
program_active = None program_active = None
if program_active and "key" in program_active: if program_active and ATTR_KEY in program_active:
self.appliance.status[BSH_ACTIVE_PROGRAM] = {"value": program_active["key"]} self.appliance.status[BSH_ACTIVE_PROGRAM] = {
ATTR_VALUE: program_active[ATTR_KEY]
}
self.appliance.listen_events(callback=self.event_callback) self.appliance.listen_events(callback=self.event_callback)
def event_callback(self, appliance): def event_callback(self, appliance):
@ -130,7 +150,7 @@ class DeviceWithPrograms(HomeConnectDevice):
There will be one switch for each program. There will be one switch for each program.
""" """
programs = self.get_programs_available() programs = self.get_programs_available()
return [{"device": self, "program_name": p["name"]} for p in programs] return [{ATTR_DEVICE: self, "program_name": p["name"]} for p in programs]
def get_program_sensors(self): def get_program_sensors(self):
"""Get a dictionary with info about program sensors. """Get a dictionary with info about program sensors.
@ -145,13 +165,13 @@ class DeviceWithPrograms(HomeConnectDevice):
} }
return [ return [
{ {
"device": self, ATTR_DEVICE: self,
"desc": k, ATTR_DESC: k,
"unit": unit, ATTR_UNIT: unit,
"key": "BSH.Common.Option.{}".format(k.replace(" ", "")), ATTR_KEY: "BSH.Common.Option.{}".format(k.replace(" ", "")),
"icon": icon, ATTR_ICON: icon,
"device_class": device_class, ATTR_DEVICE_CLASS: device_class,
"sign": sign, ATTR_SIGN: sign,
} }
for k, (unit, icon, device_class, sign) in sensors.items() for k, (unit, icon, device_class, sign) in sensors.items()
] ]
@ -165,13 +185,13 @@ class DeviceWithOpState(HomeConnectDevice):
return [ return [
{ {
"device": self, ATTR_DEVICE: self,
"desc": "Operation State", ATTR_DESC: "Operation State",
"unit": None, ATTR_UNIT: None,
"key": BSH_OPERATION_STATE, ATTR_KEY: BSH_OPERATION_STATE,
"icon": "mdi:state-machine", ATTR_ICON: "mdi:state-machine",
"device_class": None, ATTR_DEVICE_CLASS: None,
"sign": 1, ATTR_SIGN: 1,
} }
] ]
@ -182,10 +202,10 @@ class DeviceWithDoor(HomeConnectDevice):
def get_door_entity(self): def get_door_entity(self):
"""Get a dictionary with info about the door binary sensor.""" """Get a dictionary with info about the door binary sensor."""
return { return {
"device": self, ATTR_DEVICE: self,
"desc": "Door", ATTR_DESC: "Door",
"sensor_type": "door", ATTR_SENSOR_TYPE: "door",
"device_class": "door", ATTR_DEVICE_CLASS: "door",
} }
@ -194,7 +214,7 @@ class DeviceWithLight(HomeConnectDevice):
def get_light_entity(self): def get_light_entity(self):
"""Get a dictionary with info about the lighting.""" """Get a dictionary with info about the lighting."""
return {"device": self, "desc": "Light", "ambient": None} return {ATTR_DEVICE: self, ATTR_DESC: "Light", ATTR_AMBIENT: None}
class DeviceWithAmbientLight(HomeConnectDevice): class DeviceWithAmbientLight(HomeConnectDevice):
@ -202,7 +222,7 @@ class DeviceWithAmbientLight(HomeConnectDevice):
def get_ambientlight_entity(self): def get_ambientlight_entity(self):
"""Get a dictionary with info about the ambient lighting.""" """Get a dictionary with info about the ambient lighting."""
return {"device": self, "desc": "AmbientLight", "ambient": True} return {ATTR_DEVICE: self, ATTR_DESC: "AmbientLight", ATTR_AMBIENT: True}
class DeviceWithRemoteControl(HomeConnectDevice): class DeviceWithRemoteControl(HomeConnectDevice):
@ -211,9 +231,9 @@ class DeviceWithRemoteControl(HomeConnectDevice):
def get_remote_control(self): def get_remote_control(self):
"""Get a dictionary with info about the remote control sensor.""" """Get a dictionary with info about the remote control sensor."""
return { return {
"device": self, ATTR_DEVICE: self,
"desc": "Remote Control", ATTR_DESC: "Remote Control",
"sensor_type": "remote_control", ATTR_SENSOR_TYPE: "remote_control",
} }
@ -222,7 +242,11 @@ class DeviceWithRemoteStart(HomeConnectDevice):
def get_remote_start(self): def get_remote_start(self):
"""Get a dictionary with info about the remote start sensor.""" """Get a dictionary with info about the remote start sensor."""
return {"device": self, "desc": "Remote Start", "sensor_type": "remote_start"} return {
ATTR_DEVICE: self,
ATTR_DESC: "Remote Start",
ATTR_SENSOR_TYPE: "remote_start",
}
class Dryer( class Dryer(

View File

@ -2,9 +2,14 @@
import logging import logging
from homeassistant.components.binary_sensor import BinarySensorEntity from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.const import CONF_ENTITIES
from .const import ( from .const import (
ATTR_VALUE,
BSH_DOOR_STATE, BSH_DOOR_STATE,
BSH_DOOR_STATE_CLOSED,
BSH_DOOR_STATE_LOCKED,
BSH_DOOR_STATE_OPEN,
BSH_REMOTE_CONTROL_ACTIVATION_STATE, BSH_REMOTE_CONTROL_ACTIVATION_STATE,
BSH_REMOTE_START_ALLOWANCE_STATE, BSH_REMOTE_START_ALLOWANCE_STATE,
DOMAIN, DOMAIN,
@ -21,7 +26,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities = [] entities = []
hc_api = hass.data[DOMAIN][config_entry.entry_id] hc_api = hass.data[DOMAIN][config_entry.entry_id]
for device_dict in hc_api.devices: for device_dict in hc_api.devices:
entity_dicts = device_dict.get("entities", {}).get("binary_sensor", []) entity_dicts = device_dict.get(CONF_ENTITIES, {}).get("binary_sensor", [])
entities += [HomeConnectBinarySensor(**d) for d in entity_dicts] entities += [HomeConnectBinarySensor(**d) for d in entity_dicts]
return entities return entities
@ -39,11 +44,8 @@ class HomeConnectBinarySensor(HomeConnectEntity, BinarySensorEntity):
self._type = sensor_type self._type = sensor_type
if self._type == "door": if self._type == "door":
self._update_key = BSH_DOOR_STATE self._update_key = BSH_DOOR_STATE
self._false_value_list = ( self._false_value_list = (BSH_DOOR_STATE_CLOSED, BSH_DOOR_STATE_LOCKED)
"BSH.Common.EnumType.DoorState.Closed", self._true_value_list = [BSH_DOOR_STATE_OPEN]
"BSH.Common.EnumType.DoorState.Locked",
)
self._true_value_list = ["BSH.Common.EnumType.DoorState.Open"]
elif self._type == "remote_control": elif self._type == "remote_control":
self._update_key = BSH_REMOTE_CONTROL_ACTIVATION_STATE self._update_key = BSH_REMOTE_CONTROL_ACTIVATION_STATE
self._false_value_list = [False] self._false_value_list = [False]
@ -68,9 +70,9 @@ class HomeConnectBinarySensor(HomeConnectEntity, BinarySensorEntity):
state = self.device.appliance.status.get(self._update_key, {}) state = self.device.appliance.status.get(self._update_key, {})
if not state: if not state:
self._state = None self._state = None
elif state.get("value") in self._false_value_list: elif state.get(ATTR_VALUE) in self._false_value_list:
self._state = False self._state = False
elif state.get("value") in self._true_value_list: elif state.get(ATTR_VALUE) in self._true_value_list:
self._state = True self._state = True
else: else:
_LOGGER.warning( _LOGGER.warning(

View File

@ -26,5 +26,17 @@ BSH_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR = (
BSH_AMBIENT_LIGHT_CUSTOM_COLOR = "BSH.Common.Setting.AmbientLightCustomColor" BSH_AMBIENT_LIGHT_CUSTOM_COLOR = "BSH.Common.Setting.AmbientLightCustomColor"
BSH_DOOR_STATE = "BSH.Common.Status.DoorState" BSH_DOOR_STATE = "BSH.Common.Status.DoorState"
BSH_DOOR_STATE_CLOSED = "BSH.Common.EnumType.DoorState.Closed"
BSH_DOOR_STATE_LOCKED = "BSH.Common.EnumType.DoorState.Locked"
BSH_DOOR_STATE_OPEN = "BSH.Common.EnumType.DoorState.Open"
SIGNAL_UPDATE_ENTITIES = "home_connect.update_entities" SIGNAL_UPDATE_ENTITIES = "home_connect.update_entities"
ATTR_AMBIENT = "ambient"
ATTR_DESC = "desc"
ATTR_DEVICE = "device"
ATTR_KEY = "key"
ATTR_SENSOR_TYPE = "sensor_type"
ATTR_SIGN = "sign"
ATTR_UNIT = "unit"
ATTR_VALUE = "value"

View File

@ -11,9 +11,11 @@ from homeassistant.components.light import (
SUPPORT_COLOR, SUPPORT_COLOR,
LightEntity, LightEntity,
) )
from homeassistant.const import CONF_ENTITIES
import homeassistant.util.color as color_util import homeassistant.util.color as color_util
from .const import ( from .const import (
ATTR_VALUE,
BSH_AMBIENT_LIGHT_BRIGHTNESS, BSH_AMBIENT_LIGHT_BRIGHTNESS,
BSH_AMBIENT_LIGHT_COLOR, BSH_AMBIENT_LIGHT_COLOR,
BSH_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR, BSH_AMBIENT_LIGHT_COLOR_CUSTOM_COLOR,
@ -36,7 +38,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities = [] entities = []
hc_api = hass.data[DOMAIN][config_entry.entry_id] hc_api = hass.data[DOMAIN][config_entry.entry_id]
for device_dict in hc_api.devices: for device_dict in hc_api.devices:
entity_dicts = device_dict.get("entities", {}).get("light", []) entity_dicts = device_dict.get(CONF_ENTITIES, {}).get("light", [])
entity_list = [HomeConnectLight(**d) for d in entity_dicts] entity_list = [HomeConnectLight(**d) for d in entity_dicts]
entities += entity_list entities += entity_list
return entities return entities
@ -93,9 +95,7 @@ class HomeConnectLight(HomeConnectEntity, LightEntity):
_LOGGER.debug("Switching ambient light on for: %s", self.name) _LOGGER.debug("Switching ambient light on for: %s", self.name)
try: try:
await self.hass.async_add_executor_job( await self.hass.async_add_executor_job(
self.device.appliance.set_setting, self.device.appliance.set_setting, self._key, True
self._key,
True,
) )
except HomeConnectError as err: except HomeConnectError as err:
_LOGGER.error("Error while trying to turn on ambient light: %s", err) _LOGGER.error("Error while trying to turn on ambient light: %s", err)
@ -135,9 +135,7 @@ class HomeConnectLight(HomeConnectEntity, LightEntity):
brightness = 10 + ceil(kwargs[ATTR_BRIGHTNESS] / 255 * 90) brightness = 10 + ceil(kwargs[ATTR_BRIGHTNESS] / 255 * 90)
try: try:
await self.hass.async_add_executor_job( await self.hass.async_add_executor_job(
self.device.appliance.set_setting, self.device.appliance.set_setting, self._brightness_key, brightness
self._brightness_key,
brightness,
) )
except HomeConnectError as err: except HomeConnectError as err:
_LOGGER.error("Error while trying set the brightness: %s", err) _LOGGER.error("Error while trying set the brightness: %s", err)
@ -145,9 +143,7 @@ class HomeConnectLight(HomeConnectEntity, LightEntity):
_LOGGER.debug("Switching light on for: %s", self.name) _LOGGER.debug("Switching light on for: %s", self.name)
try: try:
await self.hass.async_add_executor_job( await self.hass.async_add_executor_job(
self.device.appliance.set_setting, self.device.appliance.set_setting, self._key, True
self._key,
True,
) )
except HomeConnectError as err: except HomeConnectError as err:
_LOGGER.error("Error while trying to turn on light: %s", err) _LOGGER.error("Error while trying to turn on light: %s", err)
@ -159,9 +155,7 @@ class HomeConnectLight(HomeConnectEntity, LightEntity):
_LOGGER.debug("Switching light off for: %s", self.name) _LOGGER.debug("Switching light off for: %s", self.name)
try: try:
await self.hass.async_add_executor_job( await self.hass.async_add_executor_job(
self.device.appliance.set_setting, self.device.appliance.set_setting, self._key, False
self._key,
False,
) )
except HomeConnectError as err: except HomeConnectError as err:
_LOGGER.error("Error while trying to turn off light: %s", err) _LOGGER.error("Error while trying to turn off light: %s", err)
@ -169,9 +163,9 @@ class HomeConnectLight(HomeConnectEntity, LightEntity):
async def async_update(self): async def async_update(self):
"""Update the light's status.""" """Update the light's status."""
if self.device.appliance.status.get(self._key, {}).get("value") is True: if self.device.appliance.status.get(self._key, {}).get(ATTR_VALUE) is True:
self._state = True self._state = True
elif self.device.appliance.status.get(self._key, {}).get("value") is False: elif self.device.appliance.status.get(self._key, {}).get(ATTR_VALUE) is False:
self._state = False self._state = False
else: else:
self._state = None self._state = None
@ -185,7 +179,7 @@ class HomeConnectLight(HomeConnectEntity, LightEntity):
self._hs_color = None self._hs_color = None
self._brightness = None self._brightness = None
else: else:
colorvalue = color.get("value")[1:] colorvalue = color.get(ATTR_VALUE)[1:]
rgb = color_util.rgb_hex_to_rgb_list(colorvalue) rgb = color_util.rgb_hex_to_rgb_list(colorvalue)
hsv = color_util.color_RGB_to_hsv(rgb[0], rgb[1], rgb[2]) hsv = color_util.color_RGB_to_hsv(rgb[0], rgb[1], rgb[2])
self._hs_color = [hsv[0], hsv[1]] self._hs_color = [hsv[0], hsv[1]]
@ -197,5 +191,5 @@ class HomeConnectLight(HomeConnectEntity, LightEntity):
if brightness is None: if brightness is None:
self._brightness = None self._brightness = None
else: else:
self._brightness = ceil((brightness.get("value") - 10) * 255 / 90) self._brightness = ceil((brightness.get(ATTR_VALUE) - 10) * 255 / 90)
_LOGGER.debug("Updated, new brightness: %s", self._brightness) _LOGGER.debug("Updated, new brightness: %s", self._brightness)

View File

@ -3,10 +3,10 @@
from datetime import timedelta from datetime import timedelta
import logging import logging
from homeassistant.const import DEVICE_CLASS_TIMESTAMP from homeassistant.const import CONF_ENTITIES, DEVICE_CLASS_TIMESTAMP
import homeassistant.util.dt as dt_util import homeassistant.util.dt as dt_util
from .const import BSH_OPERATION_STATE, DOMAIN from .const import ATTR_VALUE, BSH_OPERATION_STATE, DOMAIN
from .entity import HomeConnectEntity from .entity import HomeConnectEntity
_LOGGER = logging.getLogger(__name__) _LOGGER = logging.getLogger(__name__)
@ -20,7 +20,7 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities = [] entities = []
hc_api = hass.data[DOMAIN][config_entry.entry_id] hc_api = hass.data[DOMAIN][config_entry.entry_id]
for device_dict in hc_api.devices: for device_dict in hc_api.devices:
entity_dicts = device_dict.get("entities", {}).get("sensor", []) entity_dicts = device_dict.get(CONF_ENTITIES, {}).get("sensor", [])
entities += [HomeConnectSensor(**d) for d in entity_dicts] entities += [HomeConnectSensor(**d) for d in entity_dicts]
return entities return entities
@ -57,7 +57,7 @@ class HomeConnectSensor(HomeConnectEntity):
self._state = None self._state = None
else: else:
if self.device_class == DEVICE_CLASS_TIMESTAMP: if self.device_class == DEVICE_CLASS_TIMESTAMP:
if "value" not in status[self._key]: if ATTR_VALUE not in status[self._key]:
self._state = None self._state = None
elif ( elif (
self._state is not None self._state is not None
@ -68,12 +68,12 @@ class HomeConnectSensor(HomeConnectEntity):
# already past it, set state to None. # already past it, set state to None.
self._state = None self._state = None
else: else:
seconds = self._sign * float(status[self._key]["value"]) seconds = self._sign * float(status[self._key][ATTR_VALUE])
self._state = ( self._state = (
dt_util.utcnow() + timedelta(seconds=seconds) dt_util.utcnow() + timedelta(seconds=seconds)
).isoformat() ).isoformat()
else: else:
self._state = status[self._key].get("value") self._state = status[self._key].get(ATTR_VALUE)
if self._key == BSH_OPERATION_STATE: if self._key == BSH_OPERATION_STATE:
# Value comes back as an enum, we only really care about the # Value comes back as an enum, we only really care about the
# last part, so split it off # last part, so split it off

View File

@ -4,8 +4,10 @@ import logging
from homeconnect.api import HomeConnectError from homeconnect.api import HomeConnectError
from homeassistant.components.switch import SwitchEntity from homeassistant.components.switch import SwitchEntity
from homeassistant.const import CONF_DEVICE, CONF_ENTITIES
from .const import ( from .const import (
ATTR_VALUE,
BSH_ACTIVE_PROGRAM, BSH_ACTIVE_PROGRAM,
BSH_OPERATION_STATE, BSH_OPERATION_STATE,
BSH_POWER_ON, BSH_POWER_ON,
@ -25,9 +27,9 @@ async def async_setup_entry(hass, config_entry, async_add_entities):
entities = [] entities = []
hc_api = hass.data[DOMAIN][config_entry.entry_id] hc_api = hass.data[DOMAIN][config_entry.entry_id]
for device_dict in hc_api.devices: for device_dict in hc_api.devices:
entity_dicts = device_dict.get("entities", {}).get("switch", []) entity_dicts = device_dict.get(CONF_ENTITIES, {}).get("switch", [])
entity_list = [HomeConnectProgramSwitch(**d) for d in entity_dicts] entity_list = [HomeConnectProgramSwitch(**d) for d in entity_dicts]
entity_list += [HomeConnectPowerSwitch(device_dict["device"])] entity_list += [HomeConnectPowerSwitch(device_dict[CONF_DEVICE])]
entities += entity_list entities += entity_list
return entities return entities
@ -78,7 +80,7 @@ class HomeConnectProgramSwitch(HomeConnectEntity, SwitchEntity):
async def async_update(self): async def async_update(self):
"""Update the switch's status.""" """Update the switch's status."""
state = self.device.appliance.status.get(BSH_ACTIVE_PROGRAM, {}) state = self.device.appliance.status.get(BSH_ACTIVE_PROGRAM, {})
if state.get("value") == self.program_name: if state.get(ATTR_VALUE) == self.program_name:
self._state = True self._state = True
else: else:
self._state = False self._state = False
@ -103,9 +105,7 @@ class HomeConnectPowerSwitch(HomeConnectEntity, SwitchEntity):
_LOGGER.debug("Tried to switch on %s", self.name) _LOGGER.debug("Tried to switch on %s", self.name)
try: try:
await self.hass.async_add_executor_job( await self.hass.async_add_executor_job(
self.device.appliance.set_setting, self.device.appliance.set_setting, BSH_POWER_STATE, BSH_POWER_ON
BSH_POWER_STATE,
BSH_POWER_ON,
) )
except HomeConnectError as err: except HomeConnectError as err:
_LOGGER.error("Error while trying to turn on device: %s", err) _LOGGER.error("Error while trying to turn on device: %s", err)
@ -129,17 +129,17 @@ class HomeConnectPowerSwitch(HomeConnectEntity, SwitchEntity):
async def async_update(self): async def async_update(self):
"""Update the switch's status.""" """Update the switch's status."""
if ( if (
self.device.appliance.status.get(BSH_POWER_STATE, {}).get("value") self.device.appliance.status.get(BSH_POWER_STATE, {}).get(ATTR_VALUE)
== BSH_POWER_ON == BSH_POWER_ON
): ):
self._state = True self._state = True
elif ( elif (
self.device.appliance.status.get(BSH_POWER_STATE, {}).get("value") self.device.appliance.status.get(BSH_POWER_STATE, {}).get(ATTR_VALUE)
== self.device.power_off_state == self.device.power_off_state
): ):
self._state = False self._state = False
elif self.device.appliance.status.get(BSH_OPERATION_STATE, {}).get( elif self.device.appliance.status.get(BSH_OPERATION_STATE, {}).get(
"value", None ATTR_VALUE, None
) in [ ) in [
"BSH.Common.EnumType.OperationState.Ready", "BSH.Common.EnumType.OperationState.Ready",
"BSH.Common.EnumType.OperationState.DelayedStart", "BSH.Common.EnumType.OperationState.DelayedStart",
@ -151,7 +151,7 @@ class HomeConnectPowerSwitch(HomeConnectEntity, SwitchEntity):
]: ]:
self._state = True self._state = True
elif ( elif (
self.device.appliance.status.get(BSH_OPERATION_STATE, {}).get("value") self.device.appliance.status.get(BSH_OPERATION_STATE, {}).get(ATTR_VALUE)
== "BSH.Common.EnumType.OperationState.Inactive" == "BSH.Common.EnumType.OperationState.Inactive"
): ):
self._state = False self._state = False