1 """ TCP server that communicates with terminals """
3 from logging import getLogger
4 from socket import socket, AF_INET6, SOCK_STREAM, SOL_SOCKET, SO_REUSEADDR
6 from struct import pack
10 from .gps303proto import (
17 from .zmsg import Bcast, Resp
19 log = getLogger("gps303/collector")
23 """Connected socket to the terminal plus buffer and metadata"""
25 def __init__(self, sock, addr):
32 log.debug("Closing fd %d (IMEI %s)", self.sock.fileno(), self.imei)
38 """Read from the socket and parse complete messages"""
40 segment = self.sock.recv(4096)
43 "Reading from fd %d (IMEI %s): %s",
49 if not segment: # Terminal has closed connection
51 "EOF reading from fd %d (IMEI %s)",
57 self.buffer += segment
60 framestart = self.buffer.find(b"xx")
61 if framestart == -1: # No frames, return whatever we have
63 if framestart > 0: # Should not happen, report
65 'Undecodable data "%s" from fd %d (IMEI %s)',
66 self.buffer[:framestart].hex(),
70 self.buffer = self.buffer[framestart:]
71 # At this point, buffer starts with a packet
72 frameend = self.buffer.find(b"\r\n", 4)
73 if frameend == -1: # Incomplete frame, return what we have
75 packet = self.buffer[2:frameend]
76 self.buffer = self.buffer[frameend + 2 :]
77 if proto_of_message(packet) == LOGIN.PROTO:
78 self.imei = parse_message(packet).imei
80 "LOGIN from fd %d (IMEI %s)", self.sock.fileno(), self.imei
82 msgs.append((when, self.addr, packet))
85 def send(self, buffer):
87 self.sock.send(b"xx" + buffer + b"\r\n")
90 "Sending to fd %d (IMEI %s): %s",
102 def add(self, clntsock, clntaddr):
103 fd = clntsock.fileno()
104 self.by_fd[fd] = Client(clntsock, clntaddr)
108 clnt = self.by_fd[fd]
109 log.info("Stop serving fd %d (IMEI %s)", clnt.sock.fileno(), clnt.imei)
112 del self.by_imei[clnt.imei]
116 clnt = self.by_fd[fd]
121 for when, peeraddr, packet in msgs:
122 if proto_of_message(packet) == LOGIN.PROTO: # Could do blindly...
123 self.by_imei[clnt.imei] = clnt
124 result.append((clnt.imei, when, peeraddr, packet))
127 def response(self, resp):
128 if resp.imei in self.by_imei:
129 self.by_imei[resp.imei].send(resp.packet)
134 zpub = zctx.socket(zmq.PUB)
135 zpub.bind(conf.get("collector", "publishurl"))
136 zsub = zctx.socket(zmq.SUB)
137 zsub.connect(conf.get("collector", "listenurl"))
138 tcpl = socket(AF_INET6, SOCK_STREAM)
139 tcpl.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
140 tcpl.bind(("", conf.getint("collector", "port")))
142 tcpfd = tcpl.fileno()
143 poller = zmq.Poller()
144 poller.register(zsub, flags=zmq.POLLIN)
145 poller.register(tcpfd, flags=zmq.POLLIN)
152 events = poller.poll(10)
153 for sk, fl in events:
157 msg = zsub.recv(zmq.NOBLOCK)
158 tosend.append(Resp(msg))
162 clntsock, clntaddr = tcpl.accept()
163 topoll.append((clntsock, clntaddr))
165 received = clients.recv(sk)
168 "Terminal gone from fd %d (IMEI %s)", sk, imei
172 for imei, when, peeraddr, packet in received:
173 proto = proto_of_message(packet)
183 if proto == HIBERNATION.PROTO:
185 "HIBERNATION from fd %d (IMEI %s)",
190 respmsg = inline_response(packet)
191 if respmsg is not None:
193 Resp(imei=imei, packet=respmsg)
195 # poll queue consumed, make changes now
197 poller.unregister(fd)
200 clients.response(zmsg)
201 for clntsock, clntaddr in topoll:
202 fd = clients.add(clntsock, clntaddr)
204 except KeyboardInterrupt:
208 if __name__.endswith("__main__"):
209 runserver(common.init(log))