11from geventwebsocket .handler import WebSocketHandler
22import gevent
3+ import socket
34import logging
45import sys
56import os
67import signal
78from werkzeug .debug import DebuggedApplication
89
10+ from zeroconf import IPVersion , ServiceInfo , Zeroconf , get_all_addresses
11+
12+ from ..find import current_labthing
13+
914
1015class 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