Improve lists in integrations [T-U] (#113243)

pull/112833/head^2
Joost Lekkerkerker 2024-03-13 17:54:46 +01:00 committed by GitHub
parent cdba14acd4
commit 96cebdf096
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
28 changed files with 153 additions and 175 deletions

View File

@ -69,17 +69,14 @@ async def async_setup_entry(
api: Tami4EdgeAPI = data[API] api: Tami4EdgeAPI = data[API]
coordinator: Tami4EdgeWaterQualityCoordinator = data[COORDINATOR] coordinator: Tami4EdgeWaterQualityCoordinator = data[COORDINATOR]
entities = [] async_add_entities(
for entity_description in ENTITY_DESCRIPTIONS: Tami4EdgeSensorEntity(
entities.append( coordinator=coordinator,
Tami4EdgeSensorEntity( api=api,
coordinator=coordinator, entity_description=entity_description,
api=api,
entity_description=entity_description,
)
) )
for entity_description in ENTITY_DESCRIPTIONS
async_add_entities(entities) )
class Tami4EdgeSensorEntity( class Tami4EdgeSensorEntity(

View File

@ -78,12 +78,11 @@ def setup_platform(
# Get MUT information to create the sensors. # Get MUT information to create the sensors.
gateway.update() gateway.update()
entities = [] add_entities(
for mtu in gateway.data: Ted5000Sensor(gateway, name, mtu, description)
for description in SENSORS: for mtu in gateway.data
entities.append(Ted5000Sensor(gateway, name, mtu, description)) for description in SENSORS
)
add_entities(entities)
class Ted5000Sensor(SensorEntity): class Ted5000Sensor(SensorEntity):

View File

@ -186,8 +186,9 @@ class TelldusLiveClient:
self._hass.data[CONFIG_ENTRY_IS_SETUP].add(component) self._hass.data[CONFIG_ENTRY_IS_SETUP].add(component)
device_ids = [] device_ids = []
if device.is_sensor: if device.is_sensor:
for item in device.items: device_ids.extend(
device_ids.append((device.device_id, item.name, item.scale)) (device.device_id, item.name, item.scale) for item in device.items
)
else: else:
device_ids.append(device_id) device_ids.append(device_id)
for _id in device_ids: for _id in device_ids:

View File

@ -196,20 +196,16 @@ def setup_platform(
labels, use_display_name=True labels, use_display_name=True
) )
entities = [] add_entities(
TensorFlowImageProcessor(
for camera in config[CONF_SOURCE]: hass,
entities.append( camera[CONF_ENTITY_ID],
TensorFlowImageProcessor( camera.get(CONF_NAME),
hass, category_index,
camera[CONF_ENTITY_ID], config,
camera.get(CONF_NAME),
category_index,
config,
)
) )
for camera in config[CONF_SOURCE]
add_entities(entities) )
class TensorFlowImageProcessor(ImageProcessingEntity): class TensorFlowImageProcessor(ImageProcessingEntity):

View File

@ -86,22 +86,21 @@ def setup_platform(
try: try:
mgr = thermoworks_smoke.initialize_app(email, password, True, excluded) mgr = thermoworks_smoke.initialize_app(email, password, True, excluded)
# list of sensor devices
dev = []
# get list of registered devices
for serial in mgr.serials():
for variable in monitored_variables:
dev.append(ThermoworksSmokeSensor(variable, serial, mgr))
add_entities(dev, True)
except HTTPError as error: except HTTPError as error:
msg = f"{error.strerror}" msg = f"{error.strerror}"
if "EMAIL_NOT_FOUND" in msg or "INVALID_PASSWORD" in msg: if "EMAIL_NOT_FOUND" in msg or "INVALID_PASSWORD" in msg:
_LOGGER.error("Invalid email and password combination") _LOGGER.error("Invalid email and password combination")
else: else:
_LOGGER.error(msg) _LOGGER.error(msg)
else:
add_entities(
(
ThermoworksSmokeSensor(variable, serial, mgr)
for serial in mgr.serials()
for variable in monitored_variables
),
True,
)
class ThermoworksSmokeSensor(SensorEntity): class ThermoworksSmokeSensor(SensorEntity):

View File

@ -166,23 +166,22 @@ async def ws_list_datasets(
"""Get a list of thread datasets.""" """Get a list of thread datasets."""
store = await dataset_store.async_get_store(hass) store = await dataset_store.async_get_store(hass)
result = []
preferred_dataset = store.preferred_dataset preferred_dataset = store.preferred_dataset
for dataset in store.datasets.values(): result = [
result.append( {
{ "channel": dataset.channel,
"channel": dataset.channel, "created": dataset.created,
"created": dataset.created, "dataset_id": dataset.id,
"dataset_id": dataset.id, "extended_pan_id": dataset.extended_pan_id,
"extended_pan_id": dataset.extended_pan_id, "network_name": dataset.network_name,
"network_name": dataset.network_name, "pan_id": dataset.pan_id,
"pan_id": dataset.pan_id, "preferred": dataset.id == preferred_dataset,
"preferred": dataset.id == preferred_dataset, "preferred_border_agent_id": dataset.preferred_border_agent_id,
"preferred_border_agent_id": dataset.preferred_border_agent_id, "preferred_extended_address": dataset.preferred_extended_address,
"preferred_extended_address": dataset.preferred_extended_address, "source": dataset.source,
"source": dataset.source, }
} for dataset in store.datasets.values()
) ]
connection.send_result(msg["id"], {"datasets": result}) connection.send_result(msg["id"], {"datasets": result})

View File

@ -18,11 +18,8 @@ async def async_get_config_entry_diagnostics(
"""Return diagnostics for a config entry.""" """Return diagnostics for a config entry."""
tibber_connection: tibber.Tibber = hass.data[DOMAIN] tibber_connection: tibber.Tibber = hass.data[DOMAIN]
diagnostics_data = {} return {
"homes": [
homes = []
for home in tibber_connection.get_homes(only_active=False):
homes.append(
{ {
"last_data_timestamp": home.last_data_timestamp, "last_data_timestamp": home.last_data_timestamp,
"has_active_subscription": home.has_active_subscription, "has_active_subscription": home.has_active_subscription,
@ -30,7 +27,6 @@ async def async_get_config_entry_diagnostics(
"last_cons_data_timestamp": home.last_cons_data_timestamp, "last_cons_data_timestamp": home.last_cons_data_timestamp,
"country": home.country, "country": home.country,
} }
) for home in tibber_connection.get_homes(only_active=False)
diagnostics_data["homes"] = homes ]
}
return diagnostics_data

View File

@ -295,8 +295,10 @@ async def async_setup_entry(
entities.append(TibberSensorElPrice(home)) entities.append(TibberSensorElPrice(home))
if coordinator is None: if coordinator is None:
coordinator = TibberDataCoordinator(hass, tibber_connection) coordinator = TibberDataCoordinator(hass, tibber_connection)
for entity_description in SENSORS: entities.extend(
entities.append(TibberDataSensor(home, coordinator, entity_description)) TibberDataSensor(home, coordinator, entity_description)
for entity_description in SENSORS
)
if home.has_real_time_consumption: if home.has_real_time_consumption:
await home.rt_subscribe( await home.rt_subscribe(

View File

@ -36,21 +36,21 @@ async def async_setup_entry(
hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None: ) -> None:
"""Set up TotalConnect alarm panels based on a config entry.""" """Set up TotalConnect alarm panels based on a config entry."""
alarms = [] alarms: list[TotalConnectAlarm] = []
coordinator: TotalConnectDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id] coordinator: TotalConnectDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
for location_id, location in coordinator.client.locations.items(): for location_id, location in coordinator.client.locations.items():
location_name = location.location_name location_name = location.location_name
for partition_id in location.partitions: alarms.extend(
alarms.append( TotalConnectAlarm(
TotalConnectAlarm( coordinator=coordinator,
coordinator=coordinator, name=location_name,
name=location_name, location_id=location_id,
location_id=location_id, partition_id=partition_id,
partition_id=partition_id,
)
) )
for partition_id in location.partitions
)
async_add_entities(alarms) async_add_entities(alarms)

View File

@ -55,10 +55,13 @@ def setup_platform(
host = config[CONF_HOST] host = config[CONF_HOST]
py_touchline = PyTouchline() py_touchline = PyTouchline()
number_of_devices = int(py_touchline.get_number_of_devices(host)) number_of_devices = int(py_touchline.get_number_of_devices(host))
devices = [] add_entities(
for device_id in range(0, number_of_devices): (
devices.append(Touchline(PyTouchline(device_id))) Touchline(PyTouchline(device_id))
add_entities(devices, True) for device_id in range(0, number_of_devices)
),
True,
)
class Touchline(ClimateEntity): class Touchline(ClimateEntity):

View File

@ -37,8 +37,10 @@ async def async_setup_entry(
if device.is_strip: if device.is_strip:
# Historically we only add the children if the device is a strip # Historically we only add the children if the device is a strip
_LOGGER.debug("Initializing strip with %s sockets", len(device.children)) _LOGGER.debug("Initializing strip with %s sockets", len(device.children))
for child in device.children: entities.extend(
entities.append(SmartPlugSwitchChild(device, parent_coordinator, child)) SmartPlugSwitchChild(device, parent_coordinator, child)
for child in device.children
)
elif device.is_plug: elif device.is_plug:
entities.append(SmartPlugSwitch(device, parent_coordinator)) entities.append(SmartPlugSwitch(device, parent_coordinator))

View File

@ -111,13 +111,9 @@ async def async_list_contexts(
def _get_debug_traces(hass: HomeAssistant, key: str) -> list[dict[str, Any]]: def _get_debug_traces(hass: HomeAssistant, key: str) -> list[dict[str, Any]]:
"""Return a serializable list of debug traces for a script or automation.""" """Return a serializable list of debug traces for a script or automation."""
traces: list[dict[str, Any]] = []
if traces_for_key := _get_data(hass).get(key): if traces_for_key := _get_data(hass).get(key):
for trace in traces_for_key.values(): return [trace.as_short_dict() for trace in traces_for_key.values()]
traces.append(trace.as_short_dict()) return []
return traces
async def async_list_traces( async def async_list_traces(

View File

@ -26,9 +26,10 @@ async def async_get_config_entry_diagnostics(
), ),
) )
device_data: list = [] device_data: list = [
for coordinator in coordinator_data[COORDINATOR_LIST]: coordinator.device.device_info.model_number
device_data.append(coordinator.device.device_info.model_number) for coordinator in coordinator_data[COORDINATOR_LIST]
]
return { return {
"gateway_version": device.sw_version, "gateway_version": device.sw_version,

View File

@ -71,11 +71,11 @@ async def async_setup_entry(
for device_id in device_ids: for device_id in device_ids:
device = hass_data.manager.device_map[device_id] device = hass_data.manager.device_map[device_id]
if descriptions := ALARM.get(device.category): if descriptions := ALARM.get(device.category):
for description in descriptions: entities.extend(
if description.key in device.status: TuyaAlarmEntity(device, hass_data.manager, description)
entities.append( for description in descriptions
TuyaAlarmEntity(device, hass_data.manager, description) if description.key in device.status
) )
async_add_entities(entities) async_add_entities(entities)
async_discover_device([*hass_data.manager.device_map]) async_discover_device([*hass_data.manager.device_map])

View File

@ -71,11 +71,11 @@ async def async_setup_entry(
for device_id in device_ids: for device_id in device_ids:
device = hass_data.manager.device_map[device_id] device = hass_data.manager.device_map[device_id]
if descriptions := BUTTONS.get(device.category): if descriptions := BUTTONS.get(device.category):
for description in descriptions: entities.extend(
if description.key in device.status: TuyaButtonEntity(device, hass_data.manager, description)
entities.append( for description in descriptions
TuyaButtonEntity(device, hass_data.manager, description) if description.key in device.status
) )
async_add_entities(entities) async_add_entities(entities)

View File

@ -155,14 +155,14 @@ async def async_setup_entry(
for device_id in device_ids: for device_id in device_ids:
device = hass_data.manager.device_map[device_id] device = hass_data.manager.device_map[device_id]
if descriptions := COVERS.get(device.category): if descriptions := COVERS.get(device.category):
for description in descriptions: entities.extend(
TuyaCoverEntity(device, hass_data.manager, description)
for description in descriptions
if ( if (
description.key in device.function description.key in device.function
or description.key in device.status_range or description.key in device.status_range
): )
entities.append( )
TuyaCoverEntity(device, hass_data.manager, description)
)
async_add_entities(entities) async_add_entities(entities)

View File

@ -417,11 +417,11 @@ async def async_setup_entry(
for device_id in device_ids: for device_id in device_ids:
device = hass_data.manager.device_map[device_id] device = hass_data.manager.device_map[device_id]
if descriptions := LIGHTS.get(device.category): if descriptions := LIGHTS.get(device.category):
for description in descriptions: entities.extend(
if description.key in device.status: TuyaLightEntity(device, hass_data.manager, description)
entities.append( for description in descriptions
TuyaLightEntity(device, hass_data.manager, description) if description.key in device.status
) )
async_add_entities(entities) async_add_entities(entities)

View File

@ -294,11 +294,11 @@ async def async_setup_entry(
for device_id in device_ids: for device_id in device_ids:
device = hass_data.manager.device_map[device_id] device = hass_data.manager.device_map[device_id]
if descriptions := NUMBERS.get(device.category): if descriptions := NUMBERS.get(device.category):
for description in descriptions: entities.extend(
if description.key in device.status: TuyaNumberEntity(device, hass_data.manager, description)
entities.append( for description in descriptions
TuyaNumberEntity(device, hass_data.manager, description) if description.key in device.status
) )
async_add_entities(entities) async_add_entities(entities)

View File

@ -332,11 +332,11 @@ async def async_setup_entry(
for device_id in device_ids: for device_id in device_ids:
device = hass_data.manager.device_map[device_id] device = hass_data.manager.device_map[device_id]
if descriptions := SELECTS.get(device.category): if descriptions := SELECTS.get(device.category):
for description in descriptions: entities.extend(
if description.key in device.status: TuyaSelectEntity(device, hass_data.manager, description)
entities.append( for description in descriptions
TuyaSelectEntity(device, hass_data.manager, description) if description.key in device.status
) )
async_add_entities(entities) async_add_entities(entities)

View File

@ -1087,11 +1087,11 @@ async def async_setup_entry(
for device_id in device_ids: for device_id in device_ids:
device = hass_data.manager.device_map[device_id] device = hass_data.manager.device_map[device_id]
if descriptions := SENSORS.get(device.category): if descriptions := SENSORS.get(device.category):
for description in descriptions: entities.extend(
if description.key in device.status: TuyaSensorEntity(device, hass_data.manager, description)
entities.append( for description in descriptions
TuyaSensorEntity(device, hass_data.manager, description) if description.key in device.status
) )
async_add_entities(entities) async_add_entities(entities)

View File

@ -672,11 +672,11 @@ async def async_setup_entry(
for device_id in device_ids: for device_id in device_ids:
device = hass_data.manager.device_map[device_id] device = hass_data.manager.device_map[device_id]
if descriptions := SWITCHES.get(device.category): if descriptions := SWITCHES.get(device.category):
for description in descriptions: entities.extend(
if description.key in device.status: TuyaSwitchEntity(device, hass_data.manager, description)
entities.append( for description in descriptions
TuyaSwitchEntity(device, hass_data.manager, description) if description.key in device.status
) )
async_add_entities(entities) async_add_entities(entities)

View File

@ -130,10 +130,7 @@ class TwinklyLight(LightEntity):
@property @property
def effect_list(self) -> list[str]: def effect_list(self) -> list[str]:
"""Return the list of saved effects.""" """Return the list of saved effects."""
effect_list = [] return [f"{movie['id']} {movie['name']}" for movie in self._movies]
for movie in self._movies:
effect_list.append(f"{movie['id']} {movie['name']}")
return effect_list
async def async_added_to_hass(self) -> None: async def async_added_to_hass(self) -> None:
"""Device is added to hass.""" """Device is added to hass."""

View File

@ -133,17 +133,5 @@ def _find(regions, region_id):
def _make_regions_object(regions): def _make_regions_object(regions):
regions_list = [] regions = sorted(regions, key=lambda region: region["regionName"].lower())
for region in regions: return {region["regionId"]: region["regionName"] for region in regions}
regions_list.append(
{
"id": region["regionId"],
"name": region["regionName"],
}
)
regions_list = sorted(regions_list, key=lambda region: region["name"].lower())
regions_object = {}
for region in regions_list:
regions_object[region["id"]] = region["name"]
return regions_object

View File

@ -83,14 +83,14 @@ class UnifiEntityLoader:
Provide inactive clients to device tracker and switch platform. Provide inactive clients to device tracker and switch platform.
""" """
config = self.hub.config config = self.hub.config
macs: list[str] = []
entity_registry = er.async_get(self.hub.hass) entity_registry = er.async_get(self.hub.hass)
for entry in async_entries_for_config_entry( macs: list[str] = [
entity_registry, config.entry.entry_id entry.unique_id.split("-", 1)[1]
): for entry in async_entries_for_config_entry(
if entry.domain == Platform.DEVICE_TRACKER and "-" in entry.unique_id: entity_registry, config.entry.entry_id
macs.append(entry.unique_id.split("-", 1)[1]) )
if entry.domain == Platform.DEVICE_TRACKER and "-" in entry.unique_id
]
api = self.hub.api api = self.hub.api
for mac in config.option_supported_clients + config.option_block_clients + macs: for mac in config.option_supported_clients + config.option_block_clients + macs:
if mac not in api.clients and mac in api.clients_all: if mac not in api.clients and mac in api.clients_all:

View File

@ -45,12 +45,11 @@ async def async_setup_entry(
async_dispatcher_connect(hass, _ufpd(entry, DISPATCH_ADOPT), _add_new_device) async_dispatcher_connect(hass, _ufpd(entry, DISPATCH_ADOPT), _add_new_device)
) )
entities = [] async_add_entities(
for device in data.get_by_types({ModelType.LIGHT}): ProtectLight(data, device)
if device.can_write(data.api.bootstrap.auth_user): for device in data.get_by_types({ModelType.LIGHT})
entities.append(ProtectLight(data, device)) if device.can_write(data.api.bootstrap.auth_user)
)
async_add_entities(entities)
def unifi_brightness_to_hass(value: int) -> int: def unifi_brightness_to_hass(value: int) -> int:

View File

@ -130,8 +130,10 @@ def _get_doorbell_options(api: ProtectApiClient) -> list[dict[str, Any]]:
def _get_paired_camera_options(api: ProtectApiClient) -> list[dict[str, Any]]: def _get_paired_camera_options(api: ProtectApiClient) -> list[dict[str, Any]]:
options = [{"id": TYPE_EMPTY_VALUE, "name": "Not Paired"}] options = [{"id": TYPE_EMPTY_VALUE, "name": "Not Paired"}]
for camera in api.bootstrap.cameras.values(): options.extend(
options.append({"id": camera.id, "name": camera.display_name or camera.type}) {"id": camera.id, "name": camera.display_name or camera.type}
for camera in api.bootstrap.cameras.values()
)
return options return options

View File

@ -52,10 +52,11 @@ async def test_migrate_reboot_button(
assert ufp.api.update.called assert ufp.api.update.called
assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac
buttons = [] buttons = [
for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id): entity
if entity.domain == Platform.BUTTON.value: for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id)
buttons.append(entity) if entity.domain == Platform.BUTTON.value
]
assert len(buttons) == 4 assert len(buttons) == 4
assert registry.async_get(f"{Platform.BUTTON}.test_light_1_reboot_device") is None assert registry.async_get(f"{Platform.BUTTON}.test_light_1_reboot_device") is None
@ -133,10 +134,11 @@ async def test_migrate_reboot_button_no_device(
assert ufp.api.update.called assert ufp.api.update.called
assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac assert ufp.entry.unique_id == ufp.api.bootstrap.nvr.mac
buttons = [] buttons = [
for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id): entity
if entity.domain == Platform.BUTTON.value: for entity in er.async_entries_for_config_entry(registry, ufp.entry.entry_id)
buttons.append(entity) if entity.domain == Platform.BUTTON.value
]
assert len(buttons) == 3 assert len(buttons) == 3
entity = registry.async_get(f"{Platform.BUTTON}.unifiprotect_{light2_id.lower()}") entity = registry.async_get(f"{Platform.BUTTON}.unifiprotect_{light2_id.lower()}")

View File

@ -365,8 +365,7 @@ async def test_platform_setup(hass: HomeAssistant) -> None:
def add_entities(new_entities): def add_entities(new_entities):
"""Add devices to list.""" """Add devices to list."""
for dev in new_entities: entities.extend(new_entities)
entities.append(dev)
setup_ok = True setup_ok = True
try: try: