diff --git a/aiomqtt/client.py b/aiomqtt/client.py index 87d0cd9..46b0a02 100644 --- a/aiomqtt/client.py +++ b/aiomqtt/client.py @@ -511,8 +511,7 @@ async def connect(self, *, timeout: float | None = None) -> None: if self._disconnected.done(): self._disconnected = asyncio.Future() - async def disconnect(self, *, timeout: float | None = None) -> None: - """Disconnect from the broker.""" + def _early_out_on_disconnected(self) -> bool: # Early out if already disconnected... if self._disconnected.done(): disc_exc = self._disconnected.exception() @@ -520,6 +519,12 @@ async def disconnect(self, *, timeout: float | None = None) -> None: # ...by raising the error that caused the disconnect raise disc_exc # ...by returning since the disconnect was intentional + return True + return False + + async def disconnect(self, *, timeout: float | None = None) -> None: + """Disconnect from the broker.""" + if self._early_out_on_disconnected(): return # Try to gracefully disconnect from the broker rc = self._client.disconnect() @@ -1037,13 +1042,16 @@ async def __aexit__( ) -> None: """Try to gracefully disconnect from the broker.""" try: - await self.disconnect() - except MqttError as error: - # We tried to be graceful. Now there is no mercy. - self._logger.warning( - f'Could not gracefully disconnect due to "{error}". Forcing' - " disconnection." - ) + if self._early_out_on_disconnected(): + return + try: + await self.disconnect() + except MqttError as error: + # We tried to be graceful. Now there is no mercy. + self._logger.warning( + f'Could not gracefully disconnect due to "{error}". Forcing' + " disconnection." + ) finally: self._force_disconnect() self._lock.release()