1 """ Websocket Gateway """
3 from configparser import ConfigParser
4 from datetime import datetime, timezone
5 from json import dumps, loads
6 from logging import getLogger
7 from socket import socket, AF_INET6, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
9 from typing import Any, cast, Dict, List, Optional, Set, Tuple
10 from wsproto import ConnectionType, WSConnection
11 from wsproto.events import (
20 from wsproto.utilities import RemoteProtocolError
24 from .evstore import initdb, fetch
25 from .gps303proto import (
31 from .zmsg import Bcast, topic
33 log = getLogger("gps303/wsgateway")
37 def backlog(imei: str, numback: int) -> List[Dict[str, Any]]:
39 for is_incoming, timestamp, packet in fetch(
41 [(True, GPS_POSITIONING.PROTO), (False, WIFI_POSITIONING.PROTO)],
44 msg = parse_message(packet, is_incoming=is_incoming)
50 datetime.fromtimestamp(timestamp).astimezone(
54 "longitude": msg.longitude,
55 "latitude": msg.latitude,
57 if isinstance(msg, GPS_POSITIONING)
64 def try_http(data: bytes, fd: int, e: Exception) -> bytes:
67 lines = data.decode().split("\r\n")
70 op, resource, proto = request.split(" ")
72 "HTTP %s for %s, proto %s from fd %d, headers: %s",
82 f"{proto} 500 No data configured\r\n"
83 f"Content-Type: text/plain\r\n\r\n"
84 f"HTML data not configured on the server\r\n".encode()
88 with open(htmlfile, "rb") as fl:
90 length = len(htmldata)
93 f"Content-Type: text/html; charset=utf-8\r\n"
94 f"Content-Length: {len(htmldata):d}\r\n\r\n"
95 ).encode("utf-8") + htmldata
98 f"{proto} 500 File not found\r\n"
99 f"Content-Type: text/plain\r\n\r\n"
100 f"HTML file could not be opened\r\n".encode()
104 f"{proto} 400 Bad request\r\n"
105 "Content-Type: text/plain\r\n\r\n"
106 "Bad request\r\n".encode()
109 log.warning("Unparseable data from fd %d: %s", fd, data)
114 """Websocket connection to the client"""
116 def __init__(self, sock: socket, addr: Tuple[str, int]) -> None:
119 self.ws = WSConnection(ConnectionType.SERVER)
122 self.imeis: Set[str] = set()
124 def close(self) -> None:
125 log.debug("Closing fd %d", self.sock.fileno())
128 def recv(self) -> Optional[List[Dict[str, Any]]]:
130 data = self.sock.recv(4096)
133 "Reading from fd %d: %s",
137 self.ws.receive_data(None)
139 if not data: # Client has closed connection
141 "EOF reading from fd %d",
144 self.ws.receive_data(None)
147 self.ws.receive_data(data)
148 except RemoteProtocolError as e:
150 "Websocket error on fd %d, try plain http (%s)",
154 self.ws_data = try_http(data, self.sock.fileno(), e)
155 self.write() # TODO this is a hack
156 log.debug("Sending HTTP response to %d", self.sock.fileno())
160 for event in self.ws.events():
161 if isinstance(event, Request):
162 log.debug("WebSocket upgrade on fd %d", self.sock.fileno())
163 # self.ws_data += self.ws.send(event.response()) # Why not?!
164 self.ws_data += self.ws.send(AcceptConnection())
166 elif isinstance(event, (CloseConnection, Ping)):
167 log.debug("%s on fd %d", event, self.sock.fileno())
168 self.ws_data += self.ws.send(event.response())
169 elif isinstance(event, TextMessage):
170 log.debug("%s on fd %d", event, self.sock.fileno())
171 msg = loads(event.data)
173 if msg.get("type", None) == "subscribe":
174 self.imeis = set(msg.get("imei", []))
176 "subs list on fd %s is %s",
181 log.warning("%s on fd %d", event, self.sock.fileno())
184 def wants(self, imei: str) -> bool:
186 "wants %s? set is %s on fd %d",
191 return imei in self.imeis
193 def send(self, message: Dict[str, Any]) -> None:
194 if self.ready and message["imei"] in self.imeis:
195 self.ws_data += self.ws.send(Message(data=dumps(message)))
197 def write(self) -> bool:
200 sent = self.sock.send(self.ws_data)
201 self.ws_data = self.ws_data[sent:]
204 "Sending to fd %d: %s",
209 return bool(self.ws_data)
213 def __init__(self) -> None:
214 self.by_fd: Dict[int, Client] = {}
216 def add(self, clntsock: socket, clntaddr: Tuple[str, int]) -> int:
217 fd = clntsock.fileno()
218 log.info("Start serving fd %d from %s", fd, clntaddr)
219 self.by_fd[fd] = Client(clntsock, clntaddr)
222 def stop(self, fd: int) -> None:
223 clnt = self.by_fd[fd]
224 log.info("Stop serving fd %d", clnt.sock.fileno())
228 def recv(self, fd: int) -> Optional[List[Dict[str, Any]]]:
229 clnt = self.by_fd[fd]
232 def send(self, msg: Dict[str, Any]) -> Set[int]:
234 for fd, clnt in self.by_fd.items():
235 if clnt.wants(msg["imei"]):
240 def write(self, towrite: Set[int]) -> Set[int]:
242 for fd, clnt in [(fd, self.by_fd.get(fd)) for fd in towrite]:
243 if clnt and clnt.write():
247 def subs(self) -> Set[str]:
249 for clnt in self.by_fd.values():
254 def runserver(conf: ConfigParser) -> None:
257 initdb(conf.get("storage", "dbfn"))
258 htmlfile = conf.get("wsgateway", "htmlfile")
259 # Is this https://github.com/zeromq/pyzmq/issues/1627 still not fixed?!
260 zctx = zmq.Context() # type: ignore
261 zsub = zctx.socket(zmq.SUB) # type: ignore
262 zsub.connect(conf.get("collector", "publishurl"))
263 tcpl = socket(AF_INET6, SOCK_STREAM)
264 tcpl.setblocking(False)
265 tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
266 tcpl.bind(("", conf.getint("wsgateway", "port")))
268 tcpfd = tcpl.fileno()
269 poller = zmq.Poller() # type: ignore
270 poller.register(zsub, flags=zmq.POLLIN)
271 poller.register(tcpfd, flags=zmq.POLLIN)
273 activesubs: Set[str] = set()
275 towait: Set[int] = set()
277 neededsubs = clients.subs()
278 for imei in neededsubs - activesubs:
281 topic(GPS_POSITIONING.PROTO, True, imei),
285 topic(WIFI_POSITIONING.PROTO, False, imei),
289 topic(STATUS.PROTO, True, imei),
291 for imei in activesubs - neededsubs:
294 topic(GPS_POSITIONING.PROTO, True, imei),
298 topic(WIFI_POSITIONING.PROTO, False, imei),
302 topic(STATUS.PROTO, True, imei),
304 activesubs = neededsubs
305 log.debug("Subscribed to: %s", activesubs)
310 events = poller.poll()
311 for sk, fl in events:
315 zmsg = Bcast(zsub.recv(zmq.NOBLOCK))
316 msg = parse_message(zmsg.packet, zmsg.is_incoming)
317 log.debug("Got %s with %s", zmsg, msg)
318 if isinstance(msg, STATUS):
324 datetime.fromtimestamp(
326 ).astimezone(tz=timezone.utc)
337 datetime.fromtimestamp(
339 ).astimezone(tz=timezone.utc)
341 "longitude": msg.longitude,
342 "latitude": msg.latitude,
351 clntsock, clntaddr = tcpl.accept()
352 topoll.append((clntsock, clntaddr))
353 elif fl & zmq.POLLIN:
354 received = clients.recv(sk)
356 log.debug("Client gone from fd %d", sk)
360 for wsmsg in received:
361 log.debug("Received from %d: %s", sk, wsmsg)
362 if wsmsg.get("type", None) == "subscribe":
363 # Have to live w/o typeckeding from json
364 imeis = cast(List[str], wsmsg.get("imei"))
365 numback: int = wsmsg.get("backlog", 5)
367 tosend.extend(backlog(imei, numback))
369 elif fl & zmq.POLLOUT:
370 log.debug("Write now open for fd %d", sk)
374 log.debug("Stray event: %s on socket %s", fl, sk)
375 # poll queue consumed, make changes now
377 poller.unregister(fd) # type: ignore
380 log.debug("Sending to the clients: %s", wsmsg)
381 towrite |= clients.send(wsmsg)
382 for clntsock, clntaddr in topoll:
383 fd = clients.add(clntsock, clntaddr)
384 poller.register(fd, flags=zmq.POLLIN)
385 # Deal with actually writing the data out
386 trywrite = towrite - towait
387 morewait = clients.write(trywrite)
389 "towait %s, tried %s, still busy %s",
394 for fd in morewait - trywrite: # new fds waiting for write
395 poller.modify(fd, flags=zmq.POLLIN | zmq.POLLOUT) # type: ignore
396 for fd in trywrite - morewait: # no longer waiting for write
397 poller.modify(fd, flags=zmq.POLLIN) # type: ignore
400 except KeyboardInterrupt:
404 if __name__.endswith("__main__"):
405 runserver(common.init(log))