Skip to content

Commit 6f345e4

Browse files
author
Joel Collins
committed
Added a zeroconf server to the LabThings server
1 parent 96d9a1a commit 6f345e4

File tree

1 file changed

+42
-1
lines changed

1 file changed

+42
-1
lines changed

labthings/server/wsgi/gevent.py

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,58 @@
11
from geventwebsocket.handler import WebSocketHandler
22
import gevent
3+
import socket
34
import logging
45
import sys
56
import os
67
import signal
78
from werkzeug.debug import DebuggedApplication
89

10+
from zeroconf import IPVersion, ServiceInfo, Zeroconf, get_all_addresses
11+
12+
from ..find import current_labthing
13+
914

1015
class Server:
1116
def __init__(self, app):
1217
self.app = app
18+
# Find LabThing attached to app
19+
self.labthing = current_labthing(app)
1320

14-
def run(self, host="0.0.0.0", port=5000, log=None, debug=False, stop_timeout=1):
21+
def run(
22+
self,
23+
host="0.0.0.0",
24+
port=5000,
25+
log=None,
26+
debug=False,
27+
stop_timeout=1,
28+
zeroconf=True,
29+
):
1530
# Type checks
1631
port = int(port)
1732
host = str(host)
1833

1934
# Unmodified version of app
2035
app_to_run = self.app
2136

37+
# Handle zeroconf
38+
zeroconf_server = None
39+
if zeroconf and self.labthing:
40+
service_info = ServiceInfo(
41+
"_labthings._tcp.local.",
42+
f"{self.labthing.title}._labthings._tcp.local.",
43+
port=port,
44+
properties={"path": self.labthing.url_prefix},
45+
addresses=set(
46+
[
47+
socket.inet_aton(i)
48+
for i in get_all_addresses()
49+
if i not in ("127.0.0.1", "0.0.0.0")
50+
]
51+
),
52+
)
53+
zeroconf_server = Zeroconf(ip_version=IPVersion.V4Only)
54+
zeroconf_server.register_service(service_info)
55+
2256
# Handle logging
2357
if not log:
2458
log = logging.getLogger()
@@ -27,7 +61,9 @@ def run(self, host="0.0.0.0", port=5000, log=None, debug=False, stop_timeout=1):
2761
if debug:
2862
log.setLevel(logging.DEBUG)
2963
app_to_run = DebuggedApplication(self.app)
64+
logging.getLogger("zeroconf").setLevel(logging.DEBUG)
3065

66+
# Slightly more useful logger output
3167
friendlyhost = "localhost" if host == "0.0.0.0" else host
3268
logging.info("Starting LabThings WSGI Server")
3369
logging.info(f"Debug mode: {debug}")
@@ -39,6 +75,11 @@ def run(self, host="0.0.0.0", port=5000, log=None, debug=False, stop_timeout=1):
3975
)
4076

4177
def stop():
78+
# Unregister zeroconf service
79+
if zeroconf_server:
80+
zeroconf_server.unregister_service(service_info)
81+
zeroconf_server.close()
82+
# Stop WSGI server with timeout
4283
wsgi_server.stop(timeout=stop_timeout)
4384

4485
# Serve

0 commit comments

Comments
 (0)