Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion homeassistant/components/homekit/accessories.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,9 @@ def __init__(
self.entity_id = entity_id
self.hass = hass
self.debounce = {}
self._char_battery = None
self._char_charging = None
self._char_low_battery = None
self.linked_battery_sensor = self.config.get(CONF_LINKED_BATTERY_SENSOR)
self.linked_battery_charging_sensor = self.config.get(
CONF_LINKED_BATTERY_CHARGING_SENSOR
Expand Down Expand Up @@ -247,6 +250,10 @@ def update_battery(self, battery_level, battery_charging):

Only call this function if self._support_battery_level is True.
"""
if not self._char_battery:
# Battery appeared after homekit was started
return

battery_level = convert_to_float(battery_level)
if battery_level is not None:
if self._char_battery.value != battery_level:
Expand All @@ -258,7 +265,8 @@ def update_battery(self, battery_level, battery_charging):
"%s: Updated battery level to %d", self.entity_id, battery_level
)

if battery_charging is None:
# Charging state can appear after homekit was started
if battery_charging is None or not self._char_charging:
return

hk_charging = HK_CHARGING if battery_charging else HK_NOT_CHARGING
Expand Down
27 changes: 24 additions & 3 deletions tests/components/homekit/test_accessories.py
Original file line number Diff line number Diff line change
Expand Up @@ -363,9 +363,30 @@ async def test_missing_linked_battery_sensor(hass, hk_driver, caplog):
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")
assert acc._char_battery is None
assert acc._char_low_battery is None
assert acc._char_charging is None


async def test_battery_appears_after_startup(hass, hk_driver, caplog):
"""Test battery level appears after homekit is started."""
entity_id = "homekit.accessory"
hass.states.async_set(entity_id, None, {})
await hass.async_block_till_done()

acc = HomeAccessory(
hass, hk_driver, "Accessory without battery", entity_id, 2, None
)
acc.update_state = lambda x: None
assert acc._char_battery is None

await acc.run_handler()
await hass.async_block_till_done()
assert acc._char_battery is None

hass.states.async_set(entity_id, None, {ATTR_BATTERY_LEVEL: 15})
await hass.async_block_till_done()
assert acc._char_battery is None


async def test_call_service(hass, hk_driver, events):
Expand Down