diff --git a/asyncua/client/client.py b/asyncua/client/client.py index d535db8a8..5b5f01778 100644 --- a/asyncua/client/client.py +++ b/asyncua/client/client.py @@ -513,11 +513,12 @@ async def close_session(self) -> Coroutine: """ Close session """ - self._renew_channel_task.cancel() - try: - await self._renew_channel_task - except Exception: - _logger.exception("Error while closing secure channel loop") + if self._renew_channel_task: + self._renew_channel_task.cancel() + try: + await self._renew_channel_task + except Exception: + _logger.exception("Error while closing secure channel loop") return await self.uaclient.close_session(True) def get_root_node(self): diff --git a/asyncua/client/ua_client.py b/asyncua/client/ua_client.py index ebd4e1d26..27b1d8be8 100644 --- a/asyncua/client/ua_client.py +++ b/asyncua/client/ua_client.py @@ -284,7 +284,7 @@ async def close_secure_channel(self): close secure channel. It seems to trigger a shutdown of socket in most servers, so be prepare to reconnect """ - if self.protocol and self.protocol.state == UASocketProtocol.CLOSED: + if not self.protocol or self.protocol.state == UASocketProtocol.CLOSED: self.logger.warning("close_secure_channel was called but connection is closed") return return await self.protocol.close_secure_channel() @@ -313,6 +313,9 @@ async def activate_session(self, parameters): async def close_session(self, delete_subscriptions): self.logger.info("close_session") + if not self.protocol: + self.logger.warning("close_session but connection wasn't established") + return self.protocol.closed = True if self._publish_task and not self._publish_task.done(): self._publish_task.cancel() diff --git a/tests/test_connections.py b/tests/test_connections.py index b3a56e720..f9e206dec 100644 --- a/tests/test_connections.py +++ b/tests/test_connections.py @@ -23,3 +23,7 @@ async def test_max_connections_1(opc): async with Client(f'opc.tcp://127.0.0.1:{port}'): pass opc.server.iserver.isession.__class__.max_connections = 1000 + +async def safe_disconnect(): + c = Client(url="opc.tcp://example:4840") + await c.disconnect()