Skip to content

Commit

Permalink
Fixing #372
Browse files Browse the repository at this point in the history
  • Loading branch information
albertogeniola committed Apr 30, 2024
1 parent 019bb9f commit 1d3bbca
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 12 deletions.
2 changes: 1 addition & 1 deletion .version
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.4.7.1
0.4.7.2b1
28 changes: 17 additions & 11 deletions meross_iot/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@
T = TypeVar("T", bound=BaseDevice) # Declare type variable
ManagerPushNotificationHandlerType = Callable[[GenericPushNotification, List[BaseDevice], 'MerossManager'], Awaitable]

_PENDING_FUTURES = []
_PENDING_FUTURES: List["DelayedCoroFutureHandler"] = []

_DEFAULT_HEADERS = {"Content-Type": "application/json"}

Expand Down Expand Up @@ -269,9 +269,11 @@ def close(self):
_LOGGER.info("Manager stop requested.")
_LOGGER.debug("Canceling pending futures...")
for f in _PENDING_FUTURES:
if not f.cancelled():
f.cancel()
f.ensure_canceled()
_PENDING_FUTURES.clear()

# Disconnect from all mqtt clients
_LOGGER.debug("Disconnecting MQTT clients...")
for client in self._mqtt_clients.values():
client.disconnect()

Expand Down Expand Up @@ -1154,18 +1156,22 @@ def _handle_future(future: Future, result: object, exception: Exception):
future.set_result(result)


def set_future_done(coroutine, future):
coroutine.close()
if future in _PENDING_FUTURES:
_PENDING_FUTURES.remove(future)


async def delayed_execution(coro, delay):
await asyncio.sleep(delay=delay)
await coro


def _schedule_later(coroutine, start_delay, loop):
future = asyncio.run_coroutine_threadsafe(coro=delayed_execution(coro=coroutine, delay=start_delay), loop=loop)
_PENDING_FUTURES.append(future)
future.add_done_callback(functools.partial(set_future_done,coroutine))
_PENDING_FUTURES.append(DelayedCoroFutureHandler(future, coroutine))


class DelayedCoroFutureHandler:
def __init__(self, future, coroutine):
self.future = future
self.coro = coroutine

def ensure_canceled(self):
if not self.future.cancelled():
self.future.cancel()
self.coro.close()

0 comments on commit 1d3bbca

Please sign in to comment.