1 """ TCP server that communicates with terminals """
3 from logging import getLogger
4 from socket import socket, AF_INET, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
6 from struct import pack
10 from .gps303proto import HIBERNATION, LOGIN, parse_message, proto_of_message
12 log = getLogger("gps303/collector")
16 """Zmq message to broadcast what was received from the terminal"""
18 def __init__(self, imei, msg):
20 pack("B", proto_of_message(msg))
21 + ("0000000000000000" if imei is None else imei).encode()
27 """Zmq message received from a third party to send to the terminal"""
29 def __init__(self, *args, **kwargs):
30 if not kwargs and len(args) == 1 and isinstance(args[0], bytes):
31 self.imei = msg[:16].decode()
32 self.payload = msg[16:]
34 self.imei = kwargs["imei"]
35 self.payload = kwargs["payload"]
39 """Connected socket to the terminal plus buffer and metadata"""
41 def __init__(self, sock, addr):
48 log.debug("Closing fd %d (IMEI %s)", self.sock.fileno(), self.imei)
54 """Read from the socket and parse complete messages"""
56 segment = self.sock.recv(4096)
59 "Reading from fd %d (IMEI %s): %s",
65 if not segment: # Terminal has closed connection
67 "EOF reading from fd %d (IMEI %s)",
73 self.buffer += segment
76 framestart = self.buffer.find(b"xx")
77 if framestart == -1: # No frames, return whatever we have
79 if framestart > 0: # Should not happen, report
81 'Undecodable data "%s" from fd %d (IMEI %s)',
82 self.buffer[:framestart].hex(),
86 self.buffer = self.buffer[framestart:]
87 # At this point, buffer starts with a packet
88 frameend = self.buffer.find(b"\r\n", 4)
89 if frameend == -1: # Incomplete frame, return what we have
91 packet = self.buffer[2:frameend]
92 self.buffer = self.buffer[frameend + 2 :]
93 if proto_of_message(packet) == LOGIN.PROTO:
94 self.imei = parse_message(packet).imei
96 "LOGIN from fd %d (IMEI %s)", self.sock.fileno(), self.imei
101 def send(self, buffer):
103 self.sock.send(b"xx" + buffer + b"\r\n")
106 "Sending to fd %d (IMEI %s): %s",
118 def add(self, clntsock, clntaddr):
119 fd = clntsock.fileno()
120 self.by_fd[fd] = Client(clntsock, clntaddr)
124 clnt = self.by_fd[fd]
125 log.info("Stop serving fd %d (IMEI %s)", clnt.sock.fileno(), clnt.imei)
128 del self.by_imei[clnt.imei]
132 clnt = self.by_fd[fd]
138 if proto_of_message(msg) == LOGIN.PROTO: # Could do blindly...
139 self.by_imei[clnt.imei] = clnt
140 result.append((clnt.imei, msg))
143 def response(self, resp):
144 if resp.imei in self.by_imei:
145 self.by_imei[resp.imei].send(resp.payload)
150 zpub = zctx.socket(zmq.PUB)
151 zpub.bind(conf.get("collector", "publishurl"))
152 zsub = zctx.socket(zmq.SUB)
153 zsub.connect(conf.get("collector", "listenurl"))
154 tcpl = socket(AF_INET, SOCK_STREAM)
155 tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
156 tcpl.bind(("", conf.getint("collector", "port")))
158 tcpfd = tcpl.fileno()
159 poller = zmq.Poller()
160 poller.register(zsub, flags=zmq.POLLIN)
161 poller.register(tcpfd, flags=zmq.POLLIN)
168 events = poller.poll(10)
169 for sk, fl in events:
173 msg = zsub.recv(zmq.NOBLOCK)
174 tosend.append(Resp(msg))
178 clntsock, clntaddr = tcpl.accept()
179 topoll.append((clntsock, clntaddr))
181 for imei, msg in clients.recv(sk):
182 zpub.send(Bcast(imei, msg).as_bytes)
185 or proto_of_message(msg) == HIBERNATION.PROTO
188 "HIBERNATION from fd %d (IMEI %s)", sk, imei
191 elif proto_of_message(msg) == LOGIN.PROTO:
192 clients.response(Resp(imei=imei, payload=LOGIN.response()))
193 # poll queue consumed, make changes now
195 poller.unregister(fd)
198 clients.response(zmsg)
199 for clntsock, clntaddr in topoll:
200 fd = clients.add(clntsock, clntaddr)
202 except KeyboardInterrupt:
206 if __name__.endswith("__main__"):
207 runserver(common.init(log))