From 8b827268cec2a29f69ca08b80c2fe9478f1c10fd Mon Sep 17 00:00:00 2001 From: avollkopf <43980694+avollkopf@users.noreply.github.com> Date: Sat, 20 Jan 2024 15:52:43 +0100 Subject: [PATCH] check, if cbpi port is already in use prior start and log error message --- cbpi/__init__.py | 2 +- cbpi/craftbeerpi.py | 27 +++++++++++++++++++++++---- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/cbpi/__init__.py b/cbpi/__init__.py index 283212f..3f48e16 100644 --- a/cbpi/__init__.py +++ b/cbpi/__init__.py @@ -1,3 +1,3 @@ -__version__ = "4.3.2.a5" +__version__ = "4.3.2.a6" __codename__ = "Winter Storm" diff --git a/cbpi/craftbeerpi.py b/cbpi/craftbeerpi.py index 1ee8448..c11295f 100644 --- a/cbpi/craftbeerpi.py +++ b/cbpi/craftbeerpi.py @@ -1,6 +1,7 @@ import asyncio import sys +import socket try: from asyncio import set_event_loop_policy, WindowsSelectorEventLoopPolicy except ImportError: @@ -276,6 +277,22 @@ class CraftBeerPi: self.app.add_routes([web.get('/', http_index), web.static('/static', os.path.join(os.path.dirname(__file__), "static"), show_index=True)]) + + def testport(self, port=8000): + HOST = "localhost" + # Creates a new socket + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + + # Try to connect to the given host and port + if sock.connect_ex((HOST, port)) == 0: + #print("Port " + str(port) + " is open") # Connected successfully + isrunning = True + else: + #print("Port " + str(port) + " is closed") # Failed to connect because port is in use (or bad host) + isrunning = False + # Close the connection + sock.close() + return isrunning async def init_serivces(self): @@ -304,7 +321,9 @@ class CraftBeerPi: return self.app def start(self): - try: - web.run_app(self.init_serivces(), port=self.static_config.get("port", 2202)) - except Exception as e: - print("Error Starting the server: {}".format(e)) + port=self.static_config.get("port",8000) + if not self.testport(port): + web.run_app(self.init_serivces(), port=port) + else: + logging.error("Port {} is already in use! Please check, if server is already running (e.g. in automode)".format(port)) + exit(1) \ No newline at end of file