+htmlfile = None
+
+
+def backlog(imei, numback):
+ result = []
+ for is_incoming, timestamp, packet in fetch(
+ imei,
+ ((True, GPS_POSITIONING.PROTO), (False, WIFI_POSITIONING.PROTO)),
+ numback,
+ ):
+ msg = parse_message(packet, is_incoming=is_incoming)
+ result.append(
+ {
+ "imei": imei,
+ "timestamp": str(
+ datetime.fromtimestamp(timestamp).astimezone(
+ tz=timezone.utc
+ )
+ ),
+ "longitude": msg.longitude,
+ "latitude": msg.latitude,
+ }
+ )
+ return result
+
+
+def try_http(data, fd, e):
+ global htmlfile
+ try:
+ lines = data.decode().split("\r\n")
+ request = lines[0]
+ headers = lines[1:]
+ op, resource, proto = request.split(" ")
+ log.debug(
+ "HTTP %s for %s, proto %s from fd %d, headers: %s",
+ op,
+ resource,
+ proto,
+ fd,
+ headers,
+ )
+ try:
+ pos = resource.index("?")
+ resource = resource[:pos]
+ except ValueError:
+ pass
+ if op == "GET":
+ if htmlfile is None:
+ return (
+ f"{proto} 500 No data configured\r\n"
+ f"Content-Type: text/plain\r\n\r\n"
+ f"HTML data not configure on the server\r\n".encode()
+ )
+ elif resource == "/":
+ try:
+ with open(htmlfile, "rb") as fl:
+ htmldata = fl.read()
+ length = len(htmldata)
+ return (
+ f"{proto} 200 Ok\r\n"
+ f"Content-Type: text/html; charset=utf-8\r\n"
+ f"Content-Length: {len(htmldata):d}\r\n\r\n"
+ ).encode("utf-8") + htmldata
+ except OSError:
+ return (
+ f"{proto} 500 File not found\r\n"
+ f"Content-Type: text/plain\r\n\r\n"
+ f"HTML file could not be opened\r\n".encode()
+ )
+ else:
+ return (
+ f"{proto} 404 File not found\r\n"
+ f"Content-Type: text/plain\r\n\r\n"
+ f'We can only serve "/"\r\n'.encode()
+ )
+ else:
+ return (
+ f"{proto} 400 Bad request\r\n"
+ "Content-Type: text/plain\r\n\r\n"
+ "Bad request\r\n".encode()
+ )
+ except ValueError:
+ log.warning("Unparseable data from fd %d: %s", fd, data)
+ raise e