feat: check if port is busy before starting the server
Lint & Test / test (push) Successful in 1m16s
Lint & Test / test (push) Successful in 1m16s
This commit is contained in:
@@ -6,6 +6,7 @@ shows a system-tray icon with **Show UI** / **Exit** actions.
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import os
|
import os
|
||||||
|
import socket
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
@@ -43,8 +44,20 @@ def _is_restart() -> bool:
|
|||||||
return os.environ.get("WLED_RESTART", "") == "1"
|
return os.environ.get("WLED_RESTART", "") == "1"
|
||||||
|
|
||||||
|
|
||||||
|
def _check_port(host: str, port: int) -> None:
|
||||||
|
"""Exit with a clear message if the port is already in use."""
|
||||||
|
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
|
||||||
|
sock.settimeout(1)
|
||||||
|
try:
|
||||||
|
sock.bind((host, port))
|
||||||
|
except OSError:
|
||||||
|
logger.error("Port %d is already in use on %s", port, host)
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
config = get_config()
|
config = get_config()
|
||||||
|
_check_port(config.server.host, config.server.port)
|
||||||
|
|
||||||
uv_config = uvicorn.Config(
|
uv_config = uvicorn.Config(
|
||||||
"wled_controller.main:app",
|
"wled_controller.main:app",
|
||||||
@@ -55,16 +68,16 @@ def main() -> None:
|
|||||||
server = uvicorn.Server(uv_config)
|
server = uvicorn.Server(uv_config)
|
||||||
set_server(server)
|
set_server(server)
|
||||||
|
|
||||||
use_tray = PYSTRAY_AVAILABLE and (
|
use_tray = PYSTRAY_AVAILABLE and (sys.platform == "win32" or _force_tray())
|
||||||
sys.platform == "win32" or _force_tray()
|
|
||||||
)
|
|
||||||
|
|
||||||
if use_tray:
|
if use_tray:
|
||||||
logger.info("Starting with system tray icon")
|
logger.info("Starting with system tray icon")
|
||||||
|
|
||||||
# Uvicorn in a background thread
|
# Uvicorn in a background thread
|
||||||
server_thread = threading.Thread(
|
server_thread = threading.Thread(
|
||||||
target=_run_server, args=(server,), daemon=True,
|
target=_run_server,
|
||||||
|
args=(server,),
|
||||||
|
daemon=True,
|
||||||
)
|
)
|
||||||
server_thread.start()
|
server_thread.start()
|
||||||
|
|
||||||
@@ -89,9 +102,7 @@ def main() -> None:
|
|||||||
server_thread.join(timeout=10)
|
server_thread.join(timeout=10)
|
||||||
else:
|
else:
|
||||||
if not PYSTRAY_AVAILABLE:
|
if not PYSTRAY_AVAILABLE:
|
||||||
logger.info(
|
logger.info("System tray not available (install pystray for tray support)")
|
||||||
"System tray not available (install pystray for tray support)"
|
|
||||||
)
|
|
||||||
server.run()
|
server.run()
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user