Merge pull request #217 from dmunozv04/close-properly-part-2

Improve exit logic
This commit is contained in:
David
2025-01-09 14:21:12 +01:00
committed by GitHub

View File

@@ -133,15 +133,25 @@ class DeviceListener:
async def cancel(self): async def cancel(self):
self.cancelled = True self.cancelled = True
try: await self.lounge_controller.disconnect()
if self.task:
self.task.cancel() self.task.cancel()
except Exception: if self.lounge_controller.subscribe_task_watchdog:
pass self.lounge_controller.subscribe_task_watchdog.cancel()
if self.lounge_controller.subscribe_task:
self.lounge_controller.subscribe_task.cancel()
await asyncio.gather(
self.task,
self.lounge_controller.subscribe_task_watchdog,
self.lounge_controller.subscribe_task,
return_exceptions=True,
)
async def finish(devices, web_session, tcp_connector): async def finish(devices, web_session, tcp_connector):
for device in devices: await asyncio.gather(
await device.cancel() *(device.cancel() for device in devices), return_exceptions=True
)
await web_session.close() await web_session.close()
await tcp_connector.close() await tcp_connector.close()
@@ -171,9 +181,10 @@ def main(config, debug):
loop.run_forever() loop.run_forever()
except KeyboardInterrupt: except KeyboardInterrupt:
print("Cancelling tasks and exiting...") print("Cancelling tasks and exiting...")
loop.run_until_complete(finish(devices, web_session, tcp_connector))
for task in tasks: for task in tasks:
task.cancel() task.cancel()
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True)) loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
loop.run_until_complete(finish(devices, web_session, tcp_connector))
finally: finally:
loop.close() loop.close()
print("Exited")