diff --git a/homeassistant/components/homekit/accessories.py b/homeassistant/components/homekit/accessories.py index 84f0b7894c4..ddcc795d262 100644 --- a/homeassistant/components/homekit/accessories.py +++ b/homeassistant/components/homekit/accessories.py @@ -105,8 +105,18 @@ class HomeAccessory(Accessory): battery_found = self.hass.states.get(self.entity_id).attributes.get( ATTR_BATTERY_LEVEL ) + if self.linked_battery_sensor: - battery_found = self.hass.states.get(self.linked_battery_sensor).state + state = self.hass.states.get(self.linked_battery_sensor) + if state is not None: + battery_found = state.state + else: + self.linked_battery_sensor = None + _LOGGER.warning( + "%s: Battery sensor state missing: %s", + self.entity_id, + self.linked_battery_sensor, + ) if battery_found is None: return diff --git a/tests/components/homekit/test_accessories.py b/tests/components/homekit/test_accessories.py index fcc0e05b570..883d84339e5 100644 --- a/tests/components/homekit/test_accessories.py +++ b/tests/components/homekit/test_accessories.py @@ -245,6 +245,33 @@ async def test_linked_battery_sensor(hass, hk_driver, caplog): assert acc._char_charging.value == 0 +async def test_missing_linked_battery_sensor(hass, hk_driver, caplog): + """Test battery service with mising linked_battery_sensor.""" + entity_id = "homekit.accessory" + linked_battery = "sensor.battery" + hass.states.async_set(entity_id, "open") + await hass.async_block_till_done() + + acc = HomeAccessory( + hass, + hk_driver, + "Battery Service", + entity_id, + 2, + {CONF_LINKED_BATTERY_SENSOR: linked_battery}, + ) + acc.update_state = lambda x: None + assert not acc.linked_battery_sensor + + await hass.async_add_job(acc.run) + await hass.async_block_till_done() + + assert not acc.linked_battery_sensor + assert not hasattr(acc, "_char_battery") + assert not hasattr(acc, "_char_low_battery") + assert not hasattr(acc, "_char_charging") + + async def test_call_service(hass, hk_driver, events): """Test call_service method.""" entity_id = "homekit.accessory"