From 2946fa58b88f9446964a869bc2da562e8623184a Mon Sep 17 00:00:00 2001 From: Sebastien Bourdeauducq Date: Mon, 27 Oct 2014 20:37:37 +0800 Subject: [PATCH] pc_rpc: factor out asyncio server code --- artiq/devices/pdq2/pdq2-controller | 13 ++----------- artiq/management/pc_rpc.py | 21 +++++++++++++++++++++ 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/artiq/devices/pdq2/pdq2-controller b/artiq/devices/pdq2/pdq2-controller index b98661d79..e623155f0 100755 --- a/artiq/devices/pdq2/pdq2-controller +++ b/artiq/devices/pdq2/pdq2-controller @@ -10,7 +10,7 @@ import asyncio from scipy import interpolate import numpy as np -from artiq.management.pc_rpc import Server +from artiq.management.pc_rpc import simple_server_loop logger = logging.getLogger("Pdq2") @@ -355,16 +355,7 @@ def main(): dev = Pdq2(serial=args.serial) try: - loop = asyncio.get_event_loop() - try: - server = Server(dev) - loop.run_until_complete(server.start(args.bind, args.port)) - try: - loop.run_forever() - finally: - loop.run_until_complete(server.stop()) - finally: - loop.close() + simple_server_loop(dev, args.bind, args.port) finally: dev.close() diff --git a/artiq/management/pc_rpc.py b/artiq/management/pc_rpc.py index 76b5138d9..445378917 100644 --- a/artiq/management/pc_rpc.py +++ b/artiq/management/pc_rpc.py @@ -158,3 +158,24 @@ class Server: writer.write(line.encode()) finally: writer.close() + + +def simple_server_loop(target, host, port): + """Runs a server until an exception is raised (e.g. the user hits Ctrl-C). + + :param target: Object providing the RPC methods to be exposed to the + client. + :param host: Bind address of the server. + :param port: TCP port to bind to. + + """ + loop = asyncio.get_event_loop() + try: + server = Server(target) + loop.run_until_complete(server.start(host, port)) + try: + loop.run_forever() + finally: + loop.run_until_complete(server.stop()) + finally: + loop.close()