1 """ Websocket Gateway """
3 from datetime import datetime, timezone
4 from json import dumps, loads
5 from logging import getLogger
6 from socket import socket, AF_INET6, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
8 from wsproto import ConnectionType, WSConnection
9 from wsproto.events import (
17 from wsproto.utilities import RemoteProtocolError
21 from .evstore import initdb, fetch
22 from .gps303proto import (
27 from .zmsg import Bcast, topic
29 log = getLogger("gps303/wsgateway")
33 def backlog(imei, numback):
35 for is_incoming, timestamp, packet in fetch(
37 ((True, GPS_POSITIONING.PROTO), (False, WIFI_POSITIONING.PROTO)),
40 msg = parse_message(packet, is_incoming=is_incoming)
45 datetime.fromtimestamp(timestamp).astimezone(
49 "longitude": msg.longitude,
50 "latitude": msg.latitude,
56 def try_http(data, fd, e):
59 lines = data.decode().split("\r\n")
62 op, resource, proto = request.split(" ")
64 "HTTP %s for %s, proto %s from fd %d, headers: %s",
72 pos = resource.index("?")
73 resource = resource[:pos]
79 f"{proto} 500 No data configured\r\n"
80 f"Content-Type: text/plain\r\n\r\n"
81 f"HTML data not configure on the server\r\n".encode()
85 with open(htmlfile, "rb") as fl:
87 length = len(htmldata)
90 f"Content-Type: text/html; charset=utf-8\r\n"
91 f"Content-Length: {len(htmldata):d}\r\n\r\n"
92 ).encode("utf-8") + htmldata
95 f"{proto} 500 File not found\r\n"
96 f"Content-Type: text/plain\r\n\r\n"
97 f"HTML file could not be opened\r\n".encode()
101 f"{proto} 404 File not found\r\n"
102 f"Content-Type: text/plain\r\n\r\n"
103 f'We can only serve "/"\r\n'.encode()
107 f"{proto} 400 Bad request\r\n"
108 "Content-Type: text/plain\r\n\r\n"
109 "Bad request\r\n".encode()
112 log.warning("Unparseable data from fd %d: %s", fd, data)
117 """Websocket connection to the client"""
119 def __init__(self, sock, addr):
122 self.ws = WSConnection(ConnectionType.SERVER)
128 log.debug("Closing fd %d", self.sock.fileno())
133 data = self.sock.recv(4096)
136 "Reading from fd %d: %s",
140 self.ws.receive_data(None)
142 if not data: # Client has closed connection
144 "EOF reading from fd %d",
147 self.ws.receive_data(None)
150 self.ws.receive_data(data)
151 except RemoteProtocolError as e:
153 "Websocket error on fd %d, try plain http (%s)",
157 self.ws_data = try_http(data, self.sock.fileno(), e)
158 self.write() # TODO this is a hack
159 log.debug("Sending HTTP response to %d", self.sock.fileno())
163 for event in self.ws.events():
164 if isinstance(event, Request):
165 log.debug("WebSocket upgrade on fd %d", self.sock.fileno())
166 # self.ws_data += self.ws.send(event.response()) # Why not?!
167 self.ws_data += self.ws.send(AcceptConnection())
169 elif isinstance(event, (CloseConnection, Ping)):
170 log.debug("%s on fd %d", event, self.sock.fileno())
171 self.ws_data += self.ws.send(event.response())
172 elif isinstance(event, TextMessage):
173 log.debug("%s on fd %d", event, self.sock.fileno())
174 msg = loads(event.data)
176 if msg.get("type", None) == "subscribe":
177 self.imeis = set(msg.get("imei", []))
179 "subs list on fd %s is %s",
184 log.warning("%s on fd %d", event, self.sock.fileno())
187 def wants(self, imei):
189 "wants %s? set is %s on fd %d",
194 return imei in self.imeis
196 def send(self, message):
197 if self.ready and message["imei"] in self.imeis:
198 self.ws_data += self.ws.send(Message(data=dumps(message)))
203 sent = self.sock.send(self.ws_data)
204 self.ws_data = self.ws_data[sent:]
207 "Sending to fd %d: %s",
212 return bool(self.ws_data)
219 def add(self, clntsock, clntaddr):
220 fd = clntsock.fileno()
221 log.info("Start serving fd %d from %s", fd, clntaddr)
222 self.by_fd[fd] = Client(clntsock, clntaddr)
226 clnt = self.by_fd[fd]
227 log.info("Stop serving fd %d", clnt.sock.fileno())
232 clnt = self.by_fd[fd]
237 for fd, clnt in self.by_fd.items():
238 if clnt.wants(msg["imei"]):
243 def write(self, towrite):
245 for fd, clnt in [(fd, self.by_fd.get(fd)) for fd in towrite]:
252 for clnt in self.by_fd.values():
260 initdb(conf.get("storage", "dbfn"))
261 htmlfile = conf.get("wsgateway", "htmlfile")
263 zsub = zctx.socket(zmq.SUB)
264 zsub.connect(conf.get("collector", "publishurl"))
265 tcpl = socket(AF_INET6, SOCK_STREAM)
266 tcpl.setblocking(False)
267 tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
268 tcpl.bind(("", conf.getint("wsgateway", "port")))
270 tcpfd = tcpl.fileno()
271 poller = zmq.Poller()
272 poller.register(zsub, flags=zmq.POLLIN)
273 poller.register(tcpfd, flags=zmq.POLLIN)
279 neededsubs = clients.subs()
280 for imei in neededsubs - activesubs:
283 topic(GPS_POSITIONING.PROTO, True, imei),
287 topic(WIFI_POSITIONING.PROTO, False, imei),
289 for imei in activesubs - neededsubs:
292 topic(GPS_POSITIONING.PROTO, True, imei),
296 topic(WIFI_POSITIONING.PROTO, False, imei),
298 activesubs = neededsubs
299 log.debug("Subscribed to: %s", activesubs)
304 events = poller.poll()
305 for sk, fl in events:
309 zmsg = Bcast(zsub.recv(zmq.NOBLOCK))
310 msg = parse_message(zmsg.packet, zmsg.is_incoming)
311 log.debug("Got %s with %s", zmsg, msg)
316 datetime.fromtimestamp(
318 ).astimezone(tz=timezone.utc)
320 "longitude": msg.longitude,
321 "latitude": msg.latitude,
327 clntsock, clntaddr = tcpl.accept()
328 topoll.append((clntsock, clntaddr))
329 elif fl & zmq.POLLIN:
330 received = clients.recv(sk)
332 log.debug("Client gone from fd %d", sk)
337 log.debug("Received from %d: %s", sk, msg)
338 if msg.get("type", None) == "subscribe":
339 imeis = msg.get("imei")
340 numback = msg.get("backlog", 5)
342 tosend.extend(backlog(imei, numback))
344 elif fl & zmq.POLLOUT:
345 log.debug("Write now open for fd %d", sk)
349 log.debug("Stray event: %s on socket %s", fl, sk)
350 # poll queue consumed, make changes now
352 poller.unregister(fd)
355 log.debug("Sending to the clients: %s", zmsg)
356 towrite |= clients.send(zmsg)
357 for clntsock, clntaddr in topoll:
358 fd = clients.add(clntsock, clntaddr)
359 poller.register(fd, flags=zmq.POLLIN)
360 # Deal with actually writing the data out
361 trywrite = towrite - towait
362 morewait = clients.write(trywrite)
364 "towait %s, tried %s, still busy %s",
369 for fd in morewait - trywrite: # new fds waiting for write
370 poller.modify(fd, flags=zmq.POLLIN | zmq.POLLOUT)
371 for fd in trywrite - morewait: # no longer waiting for write
372 poller.modify(fd, flags=zmq.POLLIN)
375 except KeyboardInterrupt:
379 if __name__.endswith("__main__"):
380 runserver(common.init(log))