Skip to content

Commit

Permalink
Refactor and Improve connection on startup #175
Browse files Browse the repository at this point in the history
  • Loading branch information
xZetsubou committed Mar 22, 2024
1 parent 09648c9 commit ae1de60
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 21 deletions.
27 changes: 14 additions & 13 deletions custom_components/localtuya/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,13 +352,15 @@ async def setup_entities(entry_devices: dict):

# Connect to tuya devices.
connect_to_devices = [
device.async_connect() for device in hass_localtuya.devices.values()
asyncio.create_task(device.async_connect())
for device in hass_localtuya.devices.values()
]
# Update listener: add to unsub_listeners
entry_update = entry.add_update_listener(update_listener)
hass_localtuya.unsub_listeners.append(entry_update)

await asyncio.gather(*connect_to_devices)
if connect_to_devices:
await asyncio.wait(connect_to_devices, return_when=asyncio.FIRST_COMPLETED)

await setup_entities(entry.data[CONF_DEVICES])

Expand All @@ -375,20 +377,21 @@ async def async_unload_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
hass_data: HassLocalTuyaData = hass.data[DOMAIN][entry.entry_id]

for dev in hass_data.devices.values():
if dev.connected:
disconnect_devices.append(dev.close())
# dev.closed = True
# if dev.connected:
disconnect_devices.append(asyncio.create_task(dev.close()))
for entity in dev._device_config.entities:
platforms[entity[CONF_PLATFORM]] = True

# Unload the platforms.
await hass.config_entries.async_unload_platforms(entry, platforms)
# Unsub events.
[unsub() for unsub in hass_data.unsub_listeners]

# Close all connection to the devices.
# Just to prevent the loop get stuck in-case it calls multiples quickly
await asyncio.gather(*disconnect_devices)
if disconnect_devices:
await asyncio.wait(disconnect_devices)

# Unsub events.
[unsub() for unsub in hass_data.unsub_listeners]
# Unload the platforms.
await hass.config_entries.async_unload_platforms(entry, platforms)

hass.data[DOMAIN].pop(entry.entry_id)

Expand Down Expand Up @@ -450,9 +453,7 @@ async def _async_reconnect(now):
if check_if_device_disabled(hass, entry, dev_id):
return
if not dev.connected:
reconnect_devices.append(dev.async_connect())

await asyncio.gather(*reconnect_devices)
asyncio.create_task(dev.async_connect())

# Add unsub callbeack in unsub_listeners object.
hass_localtuya.unsub_listeners.append(
Expand Down
11 changes: 3 additions & 8 deletions custom_components/localtuya/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,6 @@ def _new_entity_handler(entity_id):
self._hass, self._async_refresh, timedelta(seconds=scan_inv)
)

self._is_closing = False
self._connect_task = None
self.debug(f"Success: connected to {host}", force=True)
if self._sub_devices:
Expand Down Expand Up @@ -404,10 +403,7 @@ async def close(self):
self._interface = None
if self._disconnect_task:
self._disconnect_task()
self.debug(
f"Closed connection with {self._device_config.name}",
force=True,
)
self.debug(f"Closed connection with {self._device_config.name}", force=True)

async def update_local_key(self):
"""Retrieve updated local_key from Cloud API and update the config_entry."""
Expand Down Expand Up @@ -539,10 +535,9 @@ def disconnected(self):
self._connect_task = None

# If it disconnects unexpectedly.
if self._is_closing is not True and not self.is_subdevice:
if not self._is_closing and not self.is_subdevice:
# Try quick reconnect.
self._is_closing = False
self._hass.add_job(self.async_connect())
async_call_later(self._hass, 1, self.async_connect)
if not self._is_closing:
self._shutdown_entities_delay = async_call_later(
self._hass, sleep_time + 3, self._shutdown_entities
Expand Down

0 comments on commit ae1de60

Please sign in to comment.