@@ -297,39 +297,49 @@ def _link_to_source(self, create_issue: bool = False) -> bool: # noqa: PLR0912
297297
298298 self .device_name = self .subentry .title
299299 else :
300- for entity in entity_registry .entities .values ():
301- if not entity .device_id or entity .device_id != self .device_id :
302- continue
303- if not entity .domain or entity .domain not in [
304- SENSOR_DOMAIN ,
305- BINARY_SENSOR_DOMAIN ,
306- ]:
307- continue
308- if not entity .platform or entity .platform == DOMAIN :
309- continue
310-
311- if entity .disabled :
312- continue
313-
314- device_class = entity .device_class or entity .original_device_class
315-
316- if entity .domain == SENSOR_DOMAIN :
317- if device_class != SensorDeviceClass .BATTERY :
318- continue
319- if entity .unit_of_measurement != PERCENTAGE :
320- continue
321- self .wrapped_battery = entity_registry .async_get (entity .entity_id )
322- break
323-
324- if entity .domain == BINARY_SENSOR_DOMAIN :
325- if device_class != BinarySensorDeviceClass .BATTERY :
326- continue
327- self .wrapped_battery_low = entity_registry .async_get (
328- entity .entity_id
300+ if self .device_id is not None :
301+ device_entities : list [RegistryEntry ] = (
302+ entity_registry .entities .get_entries_for_device_id (
303+ self .device_id , include_disabled_entities = False
329304 )
330- if self .wrapped_battery :
305+ )
306+
307+ candidates = (
308+ entity
309+ for entity in device_entities
310+ if entity .domain in [SENSOR_DOMAIN , BINARY_SENSOR_DOMAIN ]
311+ and entity .platform
312+ and entity .platform != DOMAIN
313+ )
314+
315+ # Sort entities to prioritize SENSOR_DOMAIN before BINARY_SENSOR_DOMAIN
316+ sorted_entities = sorted (
317+ candidates ,
318+ key = lambda e : (e .domain != SENSOR_DOMAIN , e .entity_id ),
319+ )
320+
321+ for entity in sorted_entities :
322+ device_class = entity .device_class or entity .original_device_class
323+
324+ if entity .domain == SENSOR_DOMAIN :
325+ if device_class != SensorDeviceClass .BATTERY :
326+ continue
327+ if entity .unit_of_measurement != PERCENTAGE :
328+ continue
329+ self .wrapped_battery = entity_registry .async_get (
330+ entity .entity_id
331+ )
331332 break
332333
334+ if entity .domain == BINARY_SENSOR_DOMAIN :
335+ if device_class != BinarySensorDeviceClass .BATTERY :
336+ continue
337+ self .wrapped_battery_low = entity_registry .async_get (
338+ entity .entity_id
339+ )
340+ if self .wrapped_battery :
341+ break
342+
333343 device_entry = None
334344 if self .device_id :
335345 device_entry = device_registry .async_get (self .device_id )
0 commit comments