From 1b72f94043bb5a36575d882be8c7072799fe4d52 Mon Sep 17 00:00:00 2001 From: alemidev Date: Thu, 18 Nov 2021 13:35:03 +0100 Subject: [PATCH] make client.run() block and run from sync --- aiocraft/__main__.py | 12 +----------- aiocraft/client.py | 15 ++++++++++----- 2 files changed, 11 insertions(+), 16 deletions(-) diff --git a/aiocraft/__main__.py b/aiocraft/__main__.py index be30fe5..d65282f 100644 --- a/aiocraft/__main__.py +++ b/aiocraft/__main__.py @@ -1,6 +1,5 @@ import sys import json -import asyncio import logging from .mc.proto.play.clientbound import PacketChat @@ -29,9 +28,6 @@ if __name__ == "__main__": logging.basicConfig(level=logging.INFO) - # TODO rework how this is started! Maybe implement client context manager? - loop = asyncio.get_event_loop() - client = Client(host, port, username=username, password=pwd) @client.on_packet(PacketChat, ConnectionState.PLAY) @@ -39,13 +35,7 @@ if __name__ == "__main__": msg = parse_chat(json.loads(packet.message), color=color) print(f"[{packet.position}] {msg}") - loop.run_until_complete(client.start()) - - try: - loop.run_until_complete(idle()) - except KeyboardInterrupt: - logging.info("Received SIGINT, stopping...") - loop.run_until_complete(client.stop()) + client.run() # will block and start asyncio event loop logging.info("Terminated") diff --git a/aiocraft/client.py b/aiocraft/client.py index 6bb58ac..7f39d68 100644 --- a/aiocraft/client.py +++ b/aiocraft/client.py @@ -120,18 +120,23 @@ class Client: if restart: await self.start() - async def run(self): - await self.start() + def run(self): + loop = asyncio.get_event_loop() - try: + loop.run_until_complete(self.start()) + + async def idle(): while self._processing: # TODO don't busywait even if it doesn't matter much await asyncio.sleep(self.options["poll-timeout"]) + + try: + loop.run_forever(idle()) except KeyboardInterrupt: self._logger.info("Received SIGINT, stopping...") else: self._logger.warning("Client terminating...") - await self.stop() + loop.run_until_complete(self.stop()) async def start(self): self._processing = True @@ -243,7 +248,7 @@ class Client: elif isinstance(packet, PacketKickDisconnect): self._logger.error("Kicked while in game") break - for packet_type in (Packet, packet.__class__): # check both callbacks for base class and instance class + for packet_type in (Packet, type(packet)): # check both callbacks for base class and instance class if packet_type in self._packet_callbacks: for cb in self._packet_callbacks[packet_type]: try: # TODO run in executor to not block