Skip to content

Commit

Permalink
refactor: shutdown entities on unexpected disconnect
Browse files Browse the repository at this point in the history
* Unused parameter of "private" method

* Use main thread loop

* Don't reconnect to offline device much too often

* _shutdown_entities shall do its job on closing

* Delay _shutdown_entities with a sleep

* Git rid of call_later logic
  • Loading branch information
Lurker00 authored Oct 7, 2024
1 parent c871639 commit 2ed259f
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions custom_components/localtuya/coordinator.py
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ async def _async_reconnect(self):
break

attempts += 1
scale = 1 if not self._subdevice_absent else 2
scale = 1 if not (self._subdevice_absent or attempts > MIN_OFFLINE_EVENTS) else 2
await asyncio.sleep(scale * RECONNECT_INTERVAL.total_seconds())

self._reconnect_task = False
Expand Down Expand Up @@ -505,10 +505,14 @@ def fire_event(event, data: dict):
data = {"dp": dpid_trigger, "value": dpid_value}
fire_event(event, data)

def _shutdown_entities(self, now=None, exc=""):
async def _shutdown_entities(self, exc=""):
"""Shutdown device entities"""
if self.is_sleep or self.connected:
return
# Delay shutdown.
if not self._is_closing:
await asyncio.sleep(3 + self._device_config.sleep_time)

if self.connected or self.is_sleep:
return

signal = f"localtuya_{self._device_config.id}"
dispatcher_send(self._hass, signal, None)
Expand Down Expand Up @@ -540,8 +544,6 @@ def status_updated(self, status: dict):
@callback
def disconnected(self, exc=""):
"""Device disconnected."""
sleep_time = self._device_config.sleep_time

self._interface = None

if self._unsub_refresh:
Expand All @@ -560,8 +562,9 @@ def disconnected(self, exc=""):
return

self._call_on_close.append(asyncio.create_task(self._async_reconnect()).cancel)
fun = partial(self._shutdown_entities, exc=exc)
self._call_on_close.append(async_call_later(self._hass, 3 + sleep_time, fun))
self._call_on_close.append(
asyncio.create_task(self._shutdown_entities(exc=exc)).cancel
)

@callback
def subdevice_state(self, state: SubdeviceState):
Expand Down

0 comments on commit 2ed259f

Please sign in to comment.