Skip to content

Commit

Permalink
Fix Mesh groups control in some cases
Browse files Browse the repository at this point in the history
  • Loading branch information
AlexxIT committed Apr 8, 2024
1 parent 3530223 commit 409fd62
Showing 1 changed file with 17 additions and 14 deletions.
31 changes: 17 additions & 14 deletions custom_components/xiaomi_gateway3/light.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import asyncio
import time
from functools import cached_property

from homeassistant.components.light import (
Expand Down Expand Up @@ -126,7 +127,7 @@ async def async_turn_off(self, transition: int = None, **kwargs):


class XLightGroup(XLight):
update_event: asyncio.Event
wait_update: bool = False

def childs(self):
return [
Expand All @@ -137,7 +138,6 @@ def childs(self):

async def async_added_to_hass(self) -> None:
await super().async_added_to_hass()
self.update_event = asyncio.Event()
for child in self.childs():
child.add_listener(self.forward_child_update)

Expand All @@ -147,24 +147,27 @@ async def async_will_remove_from_hass(self) -> None:
child.remove_listener(self.forward_child_update)

def forward_child_update(self, data: dict):
self.update_event.set()
self.device.dispatch(data)

async def wait_for_update(self, delay=10):
try:
self.update_event.clear()
async with asyncio.timeout(delay):
await self.update_event.wait()
except TimeoutError:
pass
self.wait_update = False
self.on_device_update(data)

async def wait_update_with_timeout(self, delay: float):
# thread safe wait logic, because `forward_child_update` and `async_turn_on`
# can be called from different threads and we can't use asyncio.Event here
wait_unil = time.time() + delay
while self.wait_update:
await asyncio.sleep(0.5)
if time.time() > wait_unil:
break

async def async_turn_on(self, **kwargs):
self.wait_update = True
await super().async_turn_on(**kwargs)
await self.wait_for_update()
await self.wait_update_with_timeout(10.0)

async def async_turn_off(self, **kwargs):
self.wait_update = True
await super().async_turn_off(**kwargs)
await self.wait_for_update()
await self.wait_update_with_timeout(10.0)


XEntity.NEW["light"] = XLight
Expand Down

0 comments on commit 409fd62

Please sign in to comment.