1
1
from geventwebsocket .handler import WebSocketHandler
2
2
import gevent
3
+ import socket
3
4
import logging
4
5
import sys
5
6
import os
6
7
import signal
7
8
from werkzeug .debug import DebuggedApplication
8
9
10
+ from zeroconf import IPVersion , ServiceInfo , Zeroconf , get_all_addresses
11
+
12
+ from ..find import current_labthing
13
+
9
14
10
15
class Server :
11
16
def __init__ (self , app ):
12
17
self .app = app
18
+ # Find LabThing attached to app
19
+ self .labthing = current_labthing (app )
13
20
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
+ ):
15
30
# Type checks
16
31
port = int (port )
17
32
host = str (host )
18
33
19
34
# Unmodified version of app
20
35
app_to_run = self .app
21
36
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
+
22
56
# Handle logging
23
57
if not log :
24
58
log = logging .getLogger ()
@@ -27,7 +61,9 @@ def run(self, host="0.0.0.0", port=5000, log=None, debug=False, stop_timeout=1):
27
61
if debug :
28
62
log .setLevel (logging .DEBUG )
29
63
app_to_run = DebuggedApplication (self .app )
64
+ logging .getLogger ("zeroconf" ).setLevel (logging .DEBUG )
30
65
66
+ # Slightly more useful logger output
31
67
friendlyhost = "localhost" if host == "0.0.0.0" else host
32
68
logging .info ("Starting LabThings WSGI Server" )
33
69
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):
39
75
)
40
76
41
77
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
42
83
wsgi_server .stop (timeout = stop_timeout )
43
84
44
85
# Serve
0 commit comments