Improve lists in integrations [G-H] (#113168)

This commit is contained in:
Joost Lekkerkerker 2024-03-13 17:25:27 +01:00 committed by GitHub
parent d4ae4a9cd0
commit 761933acfe
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
44 changed files with 392 additions and 433 deletions

View file

@ -27,17 +27,11 @@ async def async_setup_entry(
"""Defer sensor setup to the shared sensor module.""" """Defer sensor setup to the shared sensor module."""
coordinator = await get_coordinator(hass) coordinator = await get_coordinator(hass)
entities: list[GaragesAmsterdamSensor] = [] async_add_entities(
GaragesAmsterdamSensor(coordinator, config_entry.data["garage_name"], info_type)
for info_type in SENSORS: for info_type in SENSORS
if getattr(coordinator.data[config_entry.data["garage_name"]], info_type) != "": if getattr(coordinator.data[config_entry.data["garage_name"]], info_type) != ""
entities.append(
GaragesAmsterdamSensor(
coordinator, config_entry.data["garage_name"], info_type
) )
)
async_add_entities(entities)
class GaragesAmsterdamSensor(GaragesAmsterdamEntity, SensorEntity): class GaragesAmsterdamSensor(GaragesAmsterdamEntity, SensorEntity):

View file

@ -62,22 +62,19 @@ async def async_setup_platform(
None, None,
) )
if monitor_config: if monitor_config:
entities: list[GEMSensor] = []
channel_configs = monitor_config[CONF_CHANNELS] channel_configs = monitor_config[CONF_CHANNELS]
for sensor in channel_configs: entities: list[GEMSensor] = [
entities.append(
CurrentSensor( CurrentSensor(
monitor, monitor,
sensor[CONF_NUMBER], sensor[CONF_NUMBER],
sensor[CONF_NAME], sensor[CONF_NAME],
sensor[CONF_NET_METERING], sensor[CONF_NET_METERING],
) )
) for sensor in channel_configs
]
pulse_counter_configs = monitor_config[CONF_PULSE_COUNTERS] pulse_counter_configs = monitor_config[CONF_PULSE_COUNTERS]
for sensor in pulse_counter_configs: entities.extend(
entities.append(
PulseCounter( PulseCounter(
monitor, monitor,
sensor[CONF_NUMBER], sensor[CONF_NUMBER],
@ -86,23 +83,24 @@ async def async_setup_platform(
sensor[CONF_TIME_UNIT], sensor[CONF_TIME_UNIT],
sensor[CONF_COUNTED_QUANTITY_PER_PULSE], sensor[CONF_COUNTED_QUANTITY_PER_PULSE],
) )
for sensor in pulse_counter_configs
) )
temperature_sensor_configs = monitor_config[CONF_TEMPERATURE_SENSORS] temperature_sensor_configs = monitor_config[CONF_TEMPERATURE_SENSORS]
for sensor in temperature_sensor_configs[CONF_SENSORS]: entities.extend(
entities.append(
TemperatureSensor( TemperatureSensor(
monitor, monitor,
sensor[CONF_NUMBER], sensor[CONF_NUMBER],
sensor[CONF_NAME], sensor[CONF_NAME],
temperature_sensor_configs[CONF_TEMPERATURE_UNIT], temperature_sensor_configs[CONF_TEMPERATURE_UNIT],
) )
for sensor in temperature_sensor_configs[CONF_SENSORS]
) )
voltage_sensor_configs = monitor_config[CONF_VOLTAGE_SENSORS] voltage_sensor_configs = monitor_config[CONF_VOLTAGE_SENSORS]
for sensor in voltage_sensor_configs: entities.extend(
entities.append(
VoltageSensor(monitor, sensor[CONF_NUMBER], sensor[CONF_NAME]) VoltageSensor(monitor, sensor[CONF_NUMBER], sensor[CONF_NAME])
for sensor in voltage_sensor_configs
) )
async_add_entities(entities) async_add_entities(entities)

View file

@ -185,13 +185,11 @@ def groups_with_entity(hass: HomeAssistant, entity_id: str) -> list[str]:
if DOMAIN not in hass.data: if DOMAIN not in hass.data:
return [] return []
groups = [] return [
group.entity_id
for group in hass.data[DOMAIN].entities: for group in hass.data[DOMAIN].entities
if entity_id in group.tracking: if entity_id in group.tracking
groups.append(group.entity_id) ]
return groups
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool: async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:

View file

@ -19,11 +19,7 @@ async def async_reproduce_states(
reproduce_options: dict[str, Any] | None = None, reproduce_options: dict[str, Any] | None = None,
) -> None: ) -> None:
"""Reproduce component states.""" """Reproduce component states."""
states_copy = [] states_copy = [
for state in states:
members = get_entity_ids(hass, state.entity_id)
for member in members:
states_copy.append(
State( State(
member, member,
state.state, state.state,
@ -32,7 +28,9 @@ async def async_reproduce_states(
last_updated=state.last_updated, last_updated=state.last_updated,
context=state.context, context=state.context,
) )
) for state in states
for member in get_entity_ids(hass, state.entity_id)
]
await async_reproduce_state( await async_reproduce_state(
hass, states_copy, context=context, reproduce_options=reproduce_options hass, states_copy, context=context, reproduce_options=reproduce_options
) )

View file

@ -87,14 +87,16 @@ async def async_setup_entry(
) -> None: ) -> None:
"""Set up the habitica sensors.""" """Set up the habitica sensors."""
entities: list[SensorEntity] = []
name = config_entry.data[CONF_NAME] name = config_entry.data[CONF_NAME]
sensor_data = HabitipyData(hass.data[DOMAIN][config_entry.entry_id]) sensor_data = HabitipyData(hass.data[DOMAIN][config_entry.entry_id])
await sensor_data.update() await sensor_data.update()
for sensor_type in SENSORS_TYPES:
entities.append(HabitipySensor(name, sensor_type, sensor_data)) entities: list[SensorEntity] = [
for task_type in TASKS_TYPES: HabitipySensor(name, sensor_type, sensor_data) for sensor_type in SENSORS_TYPES
entities.append(HabitipyTaskSensor(name, task_type, sensor_data)) ]
entities.extend(
HabitipyTaskSensor(name, task_type, sensor_data) for task_type in TASKS_TYPES
)
async_add_entities(entities, True) async_add_entities(entities, True)

View file

@ -118,49 +118,47 @@ async def async_setup_entry(
entities: list[ entities: list[
HassioOSSensor | HassioAddonSensor | CoreSensor | SupervisorSensor | HostSensor HassioOSSensor | HassioAddonSensor | CoreSensor | SupervisorSensor | HostSensor
] = [] ] = [
for addon in coordinator.data[DATA_KEY_ADDONS].values():
for entity_description in ADDON_ENTITY_DESCRIPTIONS:
entities.append(
HassioAddonSensor( HassioAddonSensor(
addon=addon, addon=addon,
coordinator=coordinator, coordinator=coordinator,
entity_description=entity_description, entity_description=entity_description,
) )
) for addon in coordinator.data[DATA_KEY_ADDONS].values()
for entity_description in ADDON_ENTITY_DESCRIPTIONS
]
for entity_description in CORE_ENTITY_DESCRIPTIONS: entities.extend(
entities.append(
CoreSensor( CoreSensor(
coordinator=coordinator, coordinator=coordinator,
entity_description=entity_description, entity_description=entity_description,
) )
for entity_description in CORE_ENTITY_DESCRIPTIONS
) )
for entity_description in SUPERVISOR_ENTITY_DESCRIPTIONS: entities.extend(
entities.append(
SupervisorSensor( SupervisorSensor(
coordinator=coordinator, coordinator=coordinator,
entity_description=entity_description, entity_description=entity_description,
) )
for entity_description in SUPERVISOR_ENTITY_DESCRIPTIONS
) )
for entity_description in HOST_ENTITY_DESCRIPTIONS: entities.extend(
entities.append(
HostSensor( HostSensor(
coordinator=coordinator, coordinator=coordinator,
entity_description=entity_description, entity_description=entity_description,
) )
for entity_description in HOST_ENTITY_DESCRIPTIONS
) )
if coordinator.is_hass_os: if coordinator.is_hass_os:
for entity_description in OS_ENTITY_DESCRIPTIONS: entities.extend(
entities.append(
HassioOSSensor( HassioOSSensor(
coordinator=coordinator, coordinator=coordinator,
entity_description=entity_description, entity_description=entity_description,
) )
for entity_description in OS_ENTITY_DESCRIPTIONS
) )
async_add_entities(entities) async_add_entities(entities)

View file

@ -67,13 +67,13 @@ async def async_setup_entry(
), ),
] ]
for addon in coordinator.data[DATA_KEY_ADDONS].values(): entities.extend(
entities.append(
SupervisorAddonUpdateEntity( SupervisorAddonUpdateEntity(
addon=addon, addon=addon,
coordinator=coordinator, coordinator=coordinator,
entity_description=ENTITY_DESCRIPTION, entity_description=ENTITY_DESCRIPTION,
) )
for addon in coordinator.data[DATA_KEY_ADDONS].values()
) )
if coordinator.is_hass_os: if coordinator.is_hass_os:

View file

@ -49,11 +49,7 @@ def setup_platform(
api_key = config[CONF_API_KEY] api_key = config[CONF_API_KEY]
data = HaveIBeenPwnedData(emails, api_key) data = HaveIBeenPwnedData(emails, api_key)
devices = [] add_entities(HaveIBeenPwnedSensor(data, email) for email in emails)
for email in emails:
devices.append(HaveIBeenPwnedSensor(data, email))
add_entities(devices)
class HaveIBeenPwnedSensor(SensorEntity): class HaveIBeenPwnedSensor(SensorEntity):

View file

@ -66,11 +66,7 @@ def setup_platform(
if not disks: if not disks:
disks = [next(iter(hddtemp.data)).split("|")[0]] disks = [next(iter(hddtemp.data)).split("|")[0]]
dev = [] add_entities((HddTempSensor(name, disk, hddtemp) for disk in disks), True)
for disk in disks:
dev.append(HddTempSensor(name, disk, hddtemp))
add_entities(dev, True)
class HddTempSensor(SensorEntity): class HddTempSensor(SensorEntity):

View file

@ -86,16 +86,15 @@ async def async_setup_entry(
name = config_entry.data[CONF_NAME] name = config_entry.data[CONF_NAME]
coordinator = hass.data[DOMAIN][entry_id] coordinator = hass.data[DOMAIN][entry_id]
sensors: list[HERETravelTimeSensor] = [] sensors: list[HERETravelTimeSensor] = [
for sensor_description in sensor_descriptions(config_entry.data[CONF_MODE]):
sensors.append(
HERETravelTimeSensor( HERETravelTimeSensor(
entry_id, entry_id,
name, name,
sensor_description, sensor_description,
coordinator, coordinator,
) )
) for sensor_description in sensor_descriptions(config_entry.data[CONF_MODE])
]
sensors.append(OriginSensor(entry_id, name, coordinator)) sensors.append(OriginSensor(entry_id, name, coordinator))
sensors.append(DestinationSensor(entry_id, name, coordinator)) sensors.append(DestinationSensor(entry_id, name, coordinator))
async_add_entities(sensors) async_add_entities(sensors)

View file

@ -52,13 +52,17 @@ async def async_setup_entry(
hive = hass.data[DOMAIN][entry.entry_id] hive = hass.data[DOMAIN][entry.entry_id]
devices = hive.session.deviceList.get("binary_sensor") devices = hive.session.deviceList.get("binary_sensor")
entities = [] if not devices:
if devices: return
for description in BINARY_SENSOR_TYPES: async_add_entities(
for dev in devices: (
if dev["hiveType"] == description.key: HiveBinarySensorEntity(hive, dev, description)
entities.append(HiveBinarySensorEntity(hive, dev, description)) for dev in devices
async_add_entities(entities, True) for description in BINARY_SENSOR_TYPES
if dev["hiveType"] == description.key
),
True,
)
class HiveBinarySensorEntity(HiveEntity, BinarySensorEntity): class HiveBinarySensorEntity(HiveEntity, BinarySensorEntity):

View file

@ -59,11 +59,8 @@ async def async_setup_entry(
hive = hass.data[DOMAIN][entry.entry_id] hive = hass.data[DOMAIN][entry.entry_id]
devices = hive.session.deviceList.get("climate") devices = hive.session.deviceList.get("climate")
entities = []
if devices: if devices:
for dev in devices: async_add_entities((HiveClimateEntity(hive, dev) for dev in devices), True)
entities.append(HiveClimateEntity(hive, dev))
async_add_entities(entities, True)
platform = entity_platform.async_get_current_platform() platform = entity_platform.async_get_current_platform()

View file

@ -34,11 +34,9 @@ async def async_setup_entry(
hive: Hive = hass.data[DOMAIN][entry.entry_id] hive: Hive = hass.data[DOMAIN][entry.entry_id]
devices = hive.session.deviceList.get("light") devices = hive.session.deviceList.get("light")
entities = [] if not devices:
if devices: return
for dev in devices: async_add_entities((HiveDeviceLight(hive, dev) for dev in devices), True)
entities.append(HiveDeviceLight(hive, dev))
async_add_entities(entities, True)
class HiveDeviceLight(HiveEntity, LightEntity): class HiveDeviceLight(HiveEntity, LightEntity):

View file

@ -54,13 +54,17 @@ async def async_setup_entry(
"""Set up Hive thermostat based on a config entry.""" """Set up Hive thermostat based on a config entry."""
hive = hass.data[DOMAIN][entry.entry_id] hive = hass.data[DOMAIN][entry.entry_id]
devices = hive.session.deviceList.get("sensor") devices = hive.session.deviceList.get("sensor")
entities = [] if not devices:
if devices: return
for description in SENSOR_TYPES: async_add_entities(
for dev in devices: (
if dev["hiveType"] == description.key: HiveSensorEntity(hive, dev, description)
entities.append(HiveSensorEntity(hive, dev, description)) for dev in devices
async_add_entities(entities, True) for description in SENSOR_TYPES
if dev["hiveType"] == description.key
),
True,
)
class HiveSensorEntity(HiveEntity, SensorEntity): class HiveSensorEntity(HiveEntity, SensorEntity):

View file

@ -36,13 +36,17 @@ async def async_setup_entry(
hive = hass.data[DOMAIN][entry.entry_id] hive = hass.data[DOMAIN][entry.entry_id]
devices = hive.session.deviceList.get("switch") devices = hive.session.deviceList.get("switch")
entities = [] if not devices:
if devices: return
for description in SWITCH_TYPES: async_add_entities(
for dev in devices: (
if dev["hiveType"] == description.key: HiveSwitch(hive, dev, description)
entities.append(HiveSwitch(hive, dev, description)) for dev in devices
async_add_entities(entities, True) for description in SWITCH_TYPES
if dev["hiveType"] == description.key
),
True,
)
class HiveSwitch(HiveEntity, SwitchEntity): class HiveSwitch(HiveEntity, SwitchEntity):

View file

@ -49,11 +49,8 @@ async def async_setup_entry(
hive = hass.data[DOMAIN][entry.entry_id] hive = hass.data[DOMAIN][entry.entry_id]
devices = hive.session.deviceList.get("water_heater") devices = hive.session.deviceList.get("water_heater")
entities = []
if devices: if devices:
for dev in devices: async_add_entities((HiveWaterHeater(hive, dev) for dev in devices), True)
entities.append(HiveWaterHeater(hive, dev))
async_add_entities(entities, True)
platform = entity_platform.async_get_current_platform() platform = entity_platform.async_get_current_platform()

View file

@ -928,13 +928,15 @@ class HomeKit:
connection: tuple[str, str], connection: tuple[str, str],
) -> None: ) -> None:
"""Purge bridges that exist from failed pairing or manual resets.""" """Purge bridges that exist from failed pairing or manual resets."""
devices_to_purge = [] devices_to_purge = [
for entry in dev_reg.devices.values(): entry.id
if self._entry_id in entry.config_entries and ( for entry in dev_reg.devices.values()
if self._entry_id in entry.config_entries
and (
identifier not in entry.identifiers # type: ignore[comparison-overlap] identifier not in entry.identifiers # type: ignore[comparison-overlap]
or connection not in entry.connections or connection not in entry.connections
): )
devices_to_purge.append(entry.id) ]
for device_id in devices_to_purge: for device_id in devices_to_purge:
dev_reg.async_remove_device(device_id) dev_reg.async_remove_device(device_id)

View file

@ -326,10 +326,7 @@ def validate_media_player_features(state: State, feature_list: str) -> bool:
# Auto detected # Auto detected
return True return True
error_list = [] error_list = [feature for feature in feature_list if feature not in supported_modes]
for feature in feature_list:
if feature not in supported_modes:
error_list.append(feature)
if error_list: if error_list:
_LOGGER.error( _LOGGER.error(

View file

@ -160,7 +160,7 @@ def enumerate_stateless_switch_group(service: Service) -> list[dict[str, Any]]:
) )
) )
results = [] results: list[dict[str, Any]] = []
for idx, switch in enumerate(switches): for idx, switch in enumerate(switches):
char = switch[CharacteristicsTypes.INPUT_EVENT] char = switch[CharacteristicsTypes.INPUT_EVENT]
@ -168,14 +168,14 @@ def enumerate_stateless_switch_group(service: Service) -> list[dict[str, Any]]:
# manufacturer might not - clamp options to what they say. # manufacturer might not - clamp options to what they say.
all_values = clamp_enum_to_char(InputEventValues, char) all_values = clamp_enum_to_char(InputEventValues, char)
for event_type in all_values: results.extend(
results.append(
{ {
"characteristic": char.iid, "characteristic": char.iid,
"value": event_type, "value": event_type,
"type": f"button{idx + 1}", "type": f"button{idx + 1}",
"subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type], "subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type],
} }
for event_type in all_values
) )
return results return results
@ -188,17 +188,15 @@ def enumerate_doorbell(service: Service) -> list[dict[str, Any]]:
# manufacturer might not - clamp options to what they say. # manufacturer might not - clamp options to what they say.
all_values = clamp_enum_to_char(InputEventValues, input_event) all_values = clamp_enum_to_char(InputEventValues, input_event)
results = [] return [
for event_type in all_values:
results.append(
{ {
"characteristic": input_event.iid, "characteristic": input_event.iid,
"value": event_type, "value": event_type,
"type": "doorbell", "type": "doorbell",
"subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type], "subtype": HK_TO_HA_INPUT_EVENT_VALUES[event_type],
} }
) for event_type in all_values
return results ]
TRIGGER_FINDERS = { TRIGGER_FINDERS = {

View file

@ -118,11 +118,10 @@ async def async_setup_entry(
) )
) )
for switch in switches:
# The Apple docs say that if we number the buttons ourselves # The Apple docs say that if we number the buttons ourselves
# We do it in service label index order. `switches` is already in # We do it in service label index order. `switches` is already in
# that order. # that order.
entities.append( entities.extend(
HomeKitEventEntity( HomeKitEventEntity(
conn, conn,
switch, switch,
@ -132,6 +131,7 @@ async def async_setup_entry(
translation_key="button", translation_key="button",
), ),
) )
for switch in switches
) )
elif service.type == ServicesTypes.STATELESS_PROGRAMMABLE_SWITCH: elif service.type == ServicesTypes.STATELESS_PROGRAMMABLE_SWITCH:

View file

@ -259,9 +259,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, hass.data[DATA_HOMEMATIC].stop) hass.bus.listen_once(EVENT_HOMEASSISTANT_STOP, hass.data[DATA_HOMEMATIC].stop)
# Init homematic hubs # Init homematic hubs
entity_hubs = [] entity_hubs = [HMHub(hass, homematic, hub_name) for hub_name in conf[CONF_HOSTS]]
for hub_name in conf[CONF_HOSTS]:
entity_hubs.append(HMHub(hass, homematic, hub_name))
def _hm_service_virtualkey(service: ServiceCall) -> None: def _hm_service_virtualkey(service: ServiceCall) -> None:
"""Service to handle virtualkey servicecalls.""" """Service to handle virtualkey servicecalls."""

View file

@ -113,11 +113,7 @@ class HMThermostat(HMDevice, ClimateEntity):
@property @property
def preset_modes(self): def preset_modes(self):
"""Return a list of available preset modes.""" """Return a list of available preset modes."""
preset_modes = [] return [HM_PRESET_MAP[mode] for mode in self._hmdevice.ACTIONNODE]
for mode in self._hmdevice.ACTIONNODE:
if mode in HM_PRESET_MAP:
preset_modes.append(HM_PRESET_MAP[mode])
return preset_modes
@property @property
def current_humidity(self): def current_humidity(self):

View file

@ -23,11 +23,7 @@ def setup_platform(
if discovery_info is None: if discovery_info is None:
return return
devices = [] add_entities((HMLock(conf) for conf in discovery_info[ATTR_DISCOVER_DEVICES]), True)
for conf in discovery_info[ATTR_DISCOVER_DEVICES]:
devices.append(HMLock(conf))
add_entities(devices, True)
class HMLock(HMDevice, LockEntity): class HMLock(HMDevice, LockEntity):

View file

@ -86,14 +86,14 @@ async def async_setup_entry(
if isinstance(device, AsyncTiltVibrationSensor): if isinstance(device, AsyncTiltVibrationSensor):
entities.append(HomematicipTiltVibrationSensor(hap, device)) entities.append(HomematicipTiltVibrationSensor(hap, device))
if isinstance(device, AsyncWiredInput32): if isinstance(device, AsyncWiredInput32):
for channel in range(1, 33): entities.extend(
entities.append(
HomematicipMultiContactInterface(hap, device, channel=channel) HomematicipMultiContactInterface(hap, device, channel=channel)
for channel in range(1, 33)
) )
elif isinstance(device, AsyncFullFlushContactInterface6): elif isinstance(device, AsyncFullFlushContactInterface6):
for channel in range(1, 7): entities.extend(
entities.append(
HomematicipMultiContactInterface(hap, device, channel=channel) HomematicipMultiContactInterface(hap, device, channel=channel)
for channel in range(1, 7)
) )
elif isinstance( elif isinstance(
device, (AsyncContactInterface, AsyncFullFlushContactInterface) device, (AsyncContactInterface, AsyncFullFlushContactInterface)

View file

@ -20,13 +20,12 @@ async def async_setup_entry(
) -> None: ) -> None:
"""Set up the HomematicIP button from a config entry.""" """Set up the HomematicIP button from a config entry."""
hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id]
entities: list[HomematicipGenericEntity] = []
for device in hap.home.devices:
if isinstance(device, AsyncWallMountedGarageDoorController):
entities.append(HomematicipGarageDoorControllerButton(hap, device))
if entities: async_add_entities(
async_add_entities(entities) HomematicipGarageDoorControllerButton(hap, device)
for device in hap.home.devices
if isinstance(device, AsyncWallMountedGarageDoorController)
)
class HomematicipGarageDoorControllerButton(HomematicipGenericEntity, ButtonEntity): class HomematicipGarageDoorControllerButton(HomematicipGenericEntity, ButtonEntity):

View file

@ -51,12 +51,12 @@ async def async_setup_entry(
) -> None: ) -> None:
"""Set up the HomematicIP climate from a config entry.""" """Set up the HomematicIP climate from a config entry."""
hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id]
entities = []
for device in hap.home.groups:
if isinstance(device, AsyncHeatingGroup):
entities.append(HomematicipHeatingGroup(hap, device))
async_add_entities(entities) async_add_entities(
HomematicipHeatingGroup(hap, device)
for device in hap.home.groups
if isinstance(device, AsyncHeatingGroup)
)
class HomematicipHeatingGroup(HomematicipGenericEntity, ClimateEntity): class HomematicipHeatingGroup(HomematicipGenericEntity, ClimateEntity):

View file

@ -41,14 +41,18 @@ async def async_setup_entry(
) -> None: ) -> None:
"""Set up the HomematicIP cover from a config entry.""" """Set up the HomematicIP cover from a config entry."""
hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id]
entities: list[HomematicipGenericEntity] = [] entities: list[HomematicipGenericEntity] = [
HomematicipCoverShutterGroup(hap, group)
for group in hap.home.groups
if isinstance(group, AsyncExtendedLinkedShutterGroup)
]
for device in hap.home.devices: for device in hap.home.devices:
if isinstance(device, AsyncBlindModule): if isinstance(device, AsyncBlindModule):
entities.append(HomematicipBlindModule(hap, device)) entities.append(HomematicipBlindModule(hap, device))
elif isinstance(device, AsyncDinRailBlind4): elif isinstance(device, AsyncDinRailBlind4):
for channel in range(1, 5): entities.extend(
entities.append(
HomematicipMultiCoverSlats(hap, device, channel=channel) HomematicipMultiCoverSlats(hap, device, channel=channel)
for channel in range(1, 5)
) )
elif isinstance(device, AsyncFullFlushBlind): elif isinstance(device, AsyncFullFlushBlind):
entities.append(HomematicipCoverSlats(hap, device)) entities.append(HomematicipCoverSlats(hap, device))
@ -59,10 +63,6 @@ async def async_setup_entry(
): ):
entities.append(HomematicipGarageDoorModule(hap, device)) entities.append(HomematicipGarageDoorModule(hap, device))
for group in hap.home.groups:
if isinstance(group, AsyncExtendedLinkedShutterGroup):
entities.append(HomematicipCoverShutterGroup(hap, group))
async_add_entities(entities) async_add_entities(entities)

View file

@ -56,8 +56,10 @@ async def async_setup_entry(
) )
) )
elif isinstance(device, (AsyncWiredDimmer3, AsyncDinRailDimmer3)): elif isinstance(device, (AsyncWiredDimmer3, AsyncDinRailDimmer3)):
for channel in range(1, 4): entities.extend(
entities.append(HomematicipMultiDimmer(hap, device, channel=channel)) HomematicipMultiDimmer(hap, device, channel=channel)
for channel in range(1, 4)
)
elif isinstance( elif isinstance(
device, device,
(AsyncDimmer, AsyncPluggableDimmer, AsyncBrandDimmer, AsyncFullFlushDimmer), (AsyncDimmer, AsyncPluggableDimmer, AsyncBrandDimmer, AsyncFullFlushDimmer),

View file

@ -39,7 +39,11 @@ async def async_setup_entry(
) -> None: ) -> None:
"""Set up the HomematicIP switch from a config entry.""" """Set up the HomematicIP switch from a config entry."""
hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id] hap = hass.data[HMIPC_DOMAIN][config_entry.unique_id]
entities: list[HomematicipGenericEntity] = [] entities: list[HomematicipGenericEntity] = [
HomematicipGroupSwitch(hap, group)
for group in hap.home.groups
if isinstance(group, (AsyncExtendedLinkedSwitchingGroup, AsyncSwitchingGroup))
]
for device in hap.home.devices: for device in hap.home.devices:
if isinstance(device, AsyncBrandSwitchMeasuring): if isinstance(device, AsyncBrandSwitchMeasuring):
# BrandSwitchMeasuring inherits PlugableSwitchMeasuring # BrandSwitchMeasuring inherits PlugableSwitchMeasuring
@ -51,13 +55,17 @@ async def async_setup_entry(
): ):
entities.append(HomematicipSwitchMeasuring(hap, device)) entities.append(HomematicipSwitchMeasuring(hap, device))
elif isinstance(device, AsyncWiredSwitch8): elif isinstance(device, AsyncWiredSwitch8):
for channel in range(1, 9): entities.extend(
entities.append(HomematicipMultiSwitch(hap, device, channel=channel)) HomematicipMultiSwitch(hap, device, channel=channel)
for channel in range(1, 9)
)
elif isinstance(device, AsyncDinRailSwitch): elif isinstance(device, AsyncDinRailSwitch):
entities.append(HomematicipMultiSwitch(hap, device, channel=1)) entities.append(HomematicipMultiSwitch(hap, device, channel=1))
elif isinstance(device, AsyncDinRailSwitch4): elif isinstance(device, AsyncDinRailSwitch4):
for channel in range(1, 5): entities.extend(
entities.append(HomematicipMultiSwitch(hap, device, channel=channel)) HomematicipMultiSwitch(hap, device, channel=channel)
for channel in range(1, 5)
)
elif isinstance( elif isinstance(
device, device,
( (
@ -68,8 +76,10 @@ async def async_setup_entry(
): ):
entities.append(HomematicipSwitch(hap, device)) entities.append(HomematicipSwitch(hap, device))
elif isinstance(device, AsyncOpenCollector8Module): elif isinstance(device, AsyncOpenCollector8Module):
for channel in range(1, 9): entities.extend(
entities.append(HomematicipMultiSwitch(hap, device, channel=channel)) HomematicipMultiSwitch(hap, device, channel=channel)
for channel in range(1, 9)
)
elif isinstance( elif isinstance(
device, device,
( (
@ -79,12 +89,10 @@ async def async_setup_entry(
AsyncMultiIOBox, AsyncMultiIOBox,
), ),
): ):
for channel in range(1, 3): entities.extend(
entities.append(HomematicipMultiSwitch(hap, device, channel=channel)) HomematicipMultiSwitch(hap, device, channel=channel)
for channel in range(1, 3)
for group in hap.home.groups: )
if isinstance(group, (AsyncExtendedLinkedSwitchingGroup, AsyncSwitchingGroup)):
entities.append(HomematicipGroupSwitch(hap, group))
async_add_entities(entities) async_add_entities(entities)

View file

@ -86,14 +86,13 @@ async def async_setup_entry(
) -> None: ) -> None:
"""Set up the Honeywell thermostat.""" """Set up the Honeywell thermostat."""
data: HoneywellData = hass.data[DOMAIN][config_entry.entry_id] data: HoneywellData = hass.data[DOMAIN][config_entry.entry_id]
sensors = []
for device in data.devices.values(): async_add_entities(
for description in SENSOR_TYPES: HoneywellSensor(device, description)
if getattr(device, description.key) is not None: for device in data.devices.values()
sensors.append(HoneywellSensor(device, description)) for description in SENSOR_TYPES
if getattr(device, description.key) is not None
async_add_entities(sensors) )
class HoneywellSensor(SensorEntity): class HoneywellSensor(SensorEntity):

View file

@ -674,8 +674,7 @@ async def async_setup_entry(
items = filter(key_meta.include.search, items) items = filter(key_meta.include.search, items)
if key_meta.exclude: if key_meta.exclude:
items = [x for x in items if not key_meta.exclude.search(x)] items = [x for x in items if not key_meta.exclude.search(x)]
for item in items: sensors.extend(
sensors.append(
HuaweiLteSensor( HuaweiLteSensor(
router, router,
key, key,
@ -684,6 +683,7 @@ async def async_setup_entry(
item, HuaweiSensorEntityDescription(key=item) item, HuaweiSensorEntityDescription(key=item)
), ),
) )
for item in items
) )
async_add_entities(sensors, True) async_add_entities(sensors, True)

View file

@ -81,12 +81,12 @@ class HueButtonEventEntity(HueBaseEntity, EventEntity):
# fill the event types based on the features the switch supports # fill the event types based on the features the switch supports
hue_dev_id = self.controller.get_device(self.resource.id).id hue_dev_id = self.controller.get_device(self.resource.id).id
model_id = self.bridge.api.devices[hue_dev_id].product_data.product_name model_id = self.bridge.api.devices[hue_dev_id].product_data.product_name
event_types: list[str] = [] self._attr_event_types: list[str] = [
event_type.value
for event_type in DEVICE_SPECIFIC_EVENT_TYPES.get( for event_type in DEVICE_SPECIFIC_EVENT_TYPES.get(
model_id, DEFAULT_BUTTON_EVENT_TYPES model_id, DEFAULT_BUTTON_EVENT_TYPES
): )
event_types.append(event_type.value) ]
self._attr_event_types = event_types
self._attr_translation_placeholders = { self._attr_translation_placeholders = {
"button_id": self.resource.metadata.control_id "button_id": self.resource.metadata.control_id
} }

View file

@ -90,16 +90,13 @@ def async_get_triggers(
# Get Hue device id from device identifier # Get Hue device id from device identifier
hue_dev_id = get_hue_device_id(device_entry) hue_dev_id = get_hue_device_id(device_entry)
# extract triggers from all button resources of this Hue device # extract triggers from all button resources of this Hue device
triggers = [] triggers: list[dict[str, Any]] = []
model_id = api.devices[hue_dev_id].product_data.product_name model_id = api.devices[hue_dev_id].product_data.product_name
for resource in api.devices.get_sensors(hue_dev_id): for resource in api.devices.get_sensors(hue_dev_id):
# button triggers # button triggers
if resource.type == ResourceTypes.BUTTON: if resource.type == ResourceTypes.BUTTON:
for event_type in DEVICE_SPECIFIC_EVENT_TYPES.get( triggers.extend(
model_id, DEFAULT_BUTTON_EVENT_TYPES
):
triggers.append(
{ {
CONF_DEVICE_ID: device_entry.id, CONF_DEVICE_ID: device_entry.id,
CONF_DOMAIN: DOMAIN, CONF_DOMAIN: DOMAIN,
@ -108,12 +105,13 @@ def async_get_triggers(
CONF_SUBTYPE: resource.metadata.control_id, CONF_SUBTYPE: resource.metadata.control_id,
CONF_UNIQUE_ID: resource.id, CONF_UNIQUE_ID: resource.id,
} }
for event_type in DEVICE_SPECIFIC_EVENT_TYPES.get(
model_id, DEFAULT_BUTTON_EVENT_TYPES
)
) )
# relative_rotary triggers # relative_rotary triggers
elif resource.type == ResourceTypes.RELATIVE_ROTARY: elif resource.type == ResourceTypes.RELATIVE_ROTARY:
for event_type in DEFAULT_ROTARY_EVENT_TYPES: triggers.extend(
for sub_type in DEFAULT_ROTARY_EVENT_SUBTYPES:
triggers.append(
{ {
CONF_DEVICE_ID: device_entry.id, CONF_DEVICE_ID: device_entry.id,
CONF_DOMAIN: DOMAIN, CONF_DOMAIN: DOMAIN,
@ -122,6 +120,8 @@ def async_get_triggers(
CONF_SUBTYPE: sub_type.value, CONF_SUBTYPE: sub_type.value,
CONF_UNIQUE_ID: resource.id, CONF_UNIQUE_ID: resource.id,
} }
for event_type in DEFAULT_ROTARY_EVENT_TYPES
for sub_type in DEFAULT_ROTARY_EVENT_SUBTYPES
) )
return triggers return triggers

View file

@ -85,9 +85,7 @@ async def async_setup_entry(
entities: list[ButtonEntity] = [] entities: list[ButtonEntity] = []
for shade in pv_entry.shade_data.values(): for shade in pv_entry.shade_data.values():
room_name = getattr(pv_entry.room_data.get(shade.room_id), ATTR_NAME, "") room_name = getattr(pv_entry.room_data.get(shade.room_id), ATTR_NAME, "")
for description in BUTTONS_SHADE: entities.extend(
if description.create_entity_fn(shade):
entities.append(
PowerviewShadeButton( PowerviewShadeButton(
pv_entry.coordinator, pv_entry.coordinator,
pv_entry.device_info, pv_entry.device_info,
@ -96,8 +94,9 @@ async def async_setup_entry(
shade.name, shade.name,
description, description,
) )
for description in BUTTONS_SHADE
if description.create_entity_fn(shade)
) )
async_add_entities(entities) async_add_entities(entities)

View file

@ -66,9 +66,7 @@ async def async_setup_entry(
entities: list[PowerViewNumber] = [] entities: list[PowerViewNumber] = []
for shade in pv_entry.shade_data.values(): for shade in pv_entry.shade_data.values():
room_name = getattr(pv_entry.room_data.get(shade.room_id), ATTR_NAME, "") room_name = getattr(pv_entry.room_data.get(shade.room_id), ATTR_NAME, "")
for description in NUMBERS: entities.extend(
if description.create_entity_fn(shade):
entities.append(
PowerViewNumber( PowerViewNumber(
pv_entry.coordinator, pv_entry.coordinator,
pv_entry.device_info, pv_entry.device_info,
@ -77,8 +75,9 @@ async def async_setup_entry(
shade.name, shade.name,
description, description,
) )
for description in NUMBERS
if description.create_entity_fn(shade)
) )
async_add_entities(entities) async_add_entities(entities)

View file

@ -68,9 +68,7 @@ async def async_setup_entry(
if not shade.has_battery_info(): if not shade.has_battery_info():
continue continue
room_name = getattr(pv_entry.room_data.get(shade.room_id), ATTR_NAME, "") room_name = getattr(pv_entry.room_data.get(shade.room_id), ATTR_NAME, "")
for description in DROPDOWNS: entities.extend(
if description.create_entity_fn(shade):
entities.append(
PowerViewSelect( PowerViewSelect(
pv_entry.coordinator, pv_entry.coordinator,
pv_entry.device_info, pv_entry.device_info,
@ -79,8 +77,9 @@ async def async_setup_entry(
shade.name, shade.name,
description, description,
) )
for description in DROPDOWNS
if description.create_entity_fn(shade)
) )
async_add_entities(entities) async_add_entities(entities)

View file

@ -88,9 +88,7 @@ async def async_setup_entry(
entities: list[PowerViewSensor] = [] entities: list[PowerViewSensor] = []
for shade in pv_entry.shade_data.values(): for shade in pv_entry.shade_data.values():
room_name = getattr(pv_entry.room_data.get(shade.room_id), ATTR_NAME, "") room_name = getattr(pv_entry.room_data.get(shade.room_id), ATTR_NAME, "")
for description in SENSORS: entities.extend(
if description.create_entity_fn(shade):
entities.append(
PowerViewSensor( PowerViewSensor(
pv_entry.coordinator, pv_entry.coordinator,
pv_entry.device_info, pv_entry.device_info,
@ -99,8 +97,9 @@ async def async_setup_entry(
shade.name, shade.name,
description, description,
) )
for description in SENSORS
if description.create_entity_fn(shade)
) )
async_add_entities(entities) async_add_entities(entities)

View file

@ -75,10 +75,10 @@ async def async_setup_entry(
entities.append( entities.append(
HydrawiseBinarySensor(coordinator, BINARY_SENSOR_STATUS, controller) HydrawiseBinarySensor(coordinator, BINARY_SENSOR_STATUS, controller)
) )
for zone in controller.zones: entities.extend(
for description in BINARY_SENSOR_TYPES:
entities.append(
HydrawiseBinarySensor(coordinator, description, controller, zone) HydrawiseBinarySensor(coordinator, description, controller, zone)
for zone in controller.zones
for description in BINARY_SENSOR_TYPES
) )
async_add_entities(entities) async_add_entities(entities)

View file

@ -100,18 +100,16 @@ async def async_setup_entry(
def instance_add(instance_num: int, instance_name: str) -> None: def instance_add(instance_num: int, instance_name: str) -> None:
"""Add entities for a new Hyperion instance.""" """Add entities for a new Hyperion instance."""
assert server_id assert server_id
switches = [] async_add_entities(
for component in COMPONENT_SWITCHES:
switches.append(
HyperionComponentSwitch( HyperionComponentSwitch(
server_id, server_id,
instance_num, instance_num,
instance_name, instance_name,
component, component,
entry_data[CONF_INSTANCE_CLIENTS][instance_num], entry_data[CONF_INSTANCE_CLIENTS][instance_num],
),
) )
async_add_entities(switches) for component in COMPONENT_SWITCHES
)
@callback @callback
def instance_remove(instance_num: int) -> None: def instance_remove(instance_num: int) -> None:

View file

@ -241,9 +241,7 @@ def test_get_significant_states_only(hass_history) -> None:
return hass.states.get(entity_id) return hass.states.get(entity_id)
start = dt_util.utcnow() - timedelta(minutes=4) start = dt_util.utcnow() - timedelta(minutes=4)
points = [] points = [start + timedelta(minutes=i) for i in range(1, 4)]
for i in range(1, 4):
points.append(start + timedelta(minutes=i))
states = [] states = []
with freeze_time(start) as freezer: with freeze_time(start) as freezer:

View file

@ -257,9 +257,7 @@ def test_get_significant_states_only(legacy_hass_history) -> None:
return hass.states.get(entity_id) return hass.states.get(entity_id)
start = dt_util.utcnow() - timedelta(minutes=4) start = dt_util.utcnow() - timedelta(minutes=4)
points = [] points = [start + timedelta(minutes=i) for i in range(1, 4)]
for i in range(1, 4):
points.append(start + timedelta(minutes=i))
states = [] states = []
with freeze_time(start) as freezer: with freeze_time(start) as freezer:

View file

@ -116,9 +116,7 @@ async def test_enumerate_remote(
}, },
] ]
for button in ("button1", "button2", "button3", "button4"): expected.extend(
for subtype in ("single_press", "double_press", "long_press"):
expected.append(
{ {
"device_id": device.id, "device_id": device.id,
"domain": "homekit_controller", "domain": "homekit_controller",
@ -127,6 +125,8 @@ async def test_enumerate_remote(
"subtype": subtype, "subtype": subtype,
"metadata": {}, "metadata": {},
} }
for button in ("button1", "button2", "button3", "button4")
for subtype in ("single_press", "double_press", "long_press")
) )
triggers = await async_get_device_automations( triggers = await async_get_device_automations(
@ -167,8 +167,7 @@ async def test_enumerate_button(
}, },
] ]
for subtype in ("single_press", "double_press", "long_press"): expected.extend(
expected.append(
{ {
"device_id": device.id, "device_id": device.id,
"domain": "homekit_controller", "domain": "homekit_controller",
@ -177,6 +176,7 @@ async def test_enumerate_button(
"subtype": subtype, "subtype": subtype,
"metadata": {}, "metadata": {},
} }
for subtype in ("single_press", "double_press", "long_press")
) )
triggers = await async_get_device_automations( triggers = await async_get_device_automations(
@ -217,8 +217,7 @@ async def test_enumerate_doorbell(
}, },
] ]
for subtype in ("single_press", "double_press", "long_press"): expected.extend(
expected.append(
{ {
"device_id": device.id, "device_id": device.id,
"domain": "homekit_controller", "domain": "homekit_controller",
@ -227,6 +226,7 @@ async def test_enumerate_doorbell(
"subtype": subtype, "subtype": subtype,
"metadata": {}, "metadata": {},
} }
for subtype in ("single_press", "double_press", "long_press")
) )
triggers = await async_get_device_automations( triggers = await async_get_device_automations(

View file

@ -171,15 +171,9 @@ class HomeTemplate(Home):
def _generate_mocks(self): def _generate_mocks(self):
"""Generate mocks for groups and devices.""" """Generate mocks for groups and devices."""
mock_devices = [] self.devices = [_get_mock(device) for device in self.devices]
for device in self.devices:
mock_devices.append(_get_mock(device))
self.devices = mock_devices
mock_groups = [] self.groups = [_get_mock(group) for group in self.groups]
for group in self.groups:
mock_groups.append(_get_mock(group))
self.groups = mock_groups
def download_configuration(self): def download_configuration(self):
"""Return the initial json config.""" """Return the initial json config."""

View file

@ -49,10 +49,7 @@ async def test_sync_turn_off(hass: HomeAssistant) -> None:
def _create_tuples(enum: Enum, constant_prefix: str) -> list[tuple[Enum, str]]: def _create_tuples(enum: Enum, constant_prefix: str) -> list[tuple[Enum, str]]:
result = [] return [(enum_field, constant_prefix) for enum_field in enum]
for enum in enum:
result.append((enum, constant_prefix))
return result
@pytest.mark.parametrize( @pytest.mark.parametrize(