forked from 7killer/ITYC-Dashboard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
nmea_proxy.py
105 lines (81 loc) · 2.64 KB
/
nmea_proxy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import http.server
import socketserver
import socket
import argparse
import logging
parser = argparse.ArgumentParser()
parser.add_argument(
'--bind',
help='Set the server interface to bind (default 0.0.0.0)')
parser.add_argument(
'--outport',
help='Set outbound port base (default 10000)')
parser.add_argument(
'--port',
help='Set the HTTP port to bind (default 8081)')
args = parser.parse_args()
HOST = (args.bind if args.bind else '0.0.0.0')
OUTPORT = (int(args.outport) if args.outport else 10000)
PORT = (int(args.port) if args.port else 8081)
connections = dict()
sockets = dict()
class NMEAHandler(http.server.BaseHTTPRequestHandler):
def do_POST(s):
content_len = int(s.headers.get('Content-Length'))
post_body = s.rfile.read(content_len)
race_id = s.path[6:9]
forward_message(int(race_id), post_body)
s.send_response(204)
s.send_header('Access-Control-Allow-Origin', '*')
s.end_headers()
def log_message(self, format, *args):
pass
def forward_message(conn_id, message):
conn = find_or_create_connection(conn_id)
if conn:
try:
conn.send(message + '\r\n'.encode('ascii'))
except Exception:
logging.info('Connection lost on port ' + str(conn_id)
+ ', closing.')
conn.close()
connections.pop(conn_id, None)
def find_or_create_connection(conn_id):
if conn_id in connections:
return connections[conn_id]
else:
conn = None
if conn_id not in sockets:
sockets[conn_id] = create_socket(conn_id)
conn = accept_connection(sockets[conn_id])
if conn:
connections[conn_id] = conn
return conn
def create_socket(conn_id):
logging.info('Creating socket for race ID ' + str(conn_id))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.setblocking(False)
sock.bind((HOST, OUTPORT + conn_id))
sock.listen(0)
return sock
def accept_connection(sock):
try:
(conn, address) = sock.accept()
logging.info('Accepted connection on port '
+ str(sock.getsockname()[1]))
return conn
except IOError:
return None
logging.basicConfig(level=logging.INFO)
logging.info("Creating Server")
server = socketserver.TCPServer(("", PORT), NMEAHandler)
logging.info("httpd listening on port " + str(PORT))
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
logging.info('Cleaning up')
server.server_close()
logging.info('Stopping httpd\n')