Debian Codegraph @

mlat/client/output.py

raw symbols SCIP
1 # -*- python -*-
2
3 # Part of mlat-client - an ADS-B multilateration client.
4 # Copyright 2015, Oliver Jowett <[email protected]>
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 import sys
20 import asyncore
21 import socket
22 import time
23 import math
24 import errno
25
26 from mlat.client.net import LoggingMixin
27 from mlat.client.util import log, monotonic_time
28 from mlat.client.synthetic_es import make_altitude_only_frame, \
29 make_position_frame_pair, make_velocity_frame, DF18, DF18ANON, DF18TRACK
30
31
32 class OutputListener(LoggingMixin, asyncore.dispatcher):
33 def __init__(self, port, connection_factory):
34 asyncore.dispatcher.__init__(self)
35 self.port = port
36
37 self.a_type = socket.SOCK_STREAM
38 try:
39 # bind to V6 so we can accept both V4 and V6
40 # (asyncore makes it a hassle to bind to more than
41 # one address here)
42 self.a_family = socket.AF_INET6
43 self.create_socket(self.a_family, self.a_type)
44 except socket.error:
45 # maybe no v6 support?
46 self.a_family = socket.AF_INET
47 self.create_socket(self.a_family, self.a_type)
48
49 try:
50 self.set_reuse_addr()
51 self.bind(('', port))
52 self.listen(5)
53 except Exception:
54 self.close()
55 raise
56
57 self.output_channels = set()
58 self.connection_factory = connection_factory
59 log('Listening for {0} on port {1}', connection_factory.describe(), port)
60
61 def handle_accept(self):
62 accepted = self.accept()
63 if not accepted:
64 return
65
66 new_socket, address = accepted
67 log('Accepted {0} from {1}:{2}', self.connection_factory.describe(), address[0], address[1])
68
69 self.output_channels.add(self.connection_factory(self, new_socket, self.a_type, self.a_family, address))
70
71 def send_position(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate,
72 callsign, squawk, error_est, nstations, anon, modeac):
73 for channel in list(self.output_channels):
74 channel.send_position(timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate,
75 callsign, squawk, error_est, nstations, anon, modeac)
76
77 def heartbeat(self, now):
78 for channel in list(self.output_channels):
79 channel.heartbeat(now)
80
81 def disconnect(self, reason=None):
82 for channel in list(self.output_channels):
83 channel.close()
84 self.close()
85
86 def connection_lost(self, child):
87 self.output_channels.discard(child)
88
89
90 class OutputConnector:
91 reconnect_interval = 30.0
92
93 def __init__(self, addr, connection_factory):
94 self.addr = addr
95 self.connection_factory = connection_factory
96
97 self.output_channel = None
98 self.next_reconnect = monotonic_time()
99 self.addrlist = []
100
101 @staticmethod
102 def describe():
103 return 'OutputConnector'
104
105 def log(self, fmt, *args, **kwargs):
106 log('{what} with {host}:{port}: ' + fmt,
107 *args,
108 what=self.describe(), host=self.addr[0], port=self.addr[1],
109 **kwargs)
110
111 def reconnect(self):
112 if len(self.addrlist) == 0:
113 try:
114 self.addrlist = socket.getaddrinfo(host=self.addr[0],
115 port=self.addr[1],
116 family=socket.AF_UNSPEC,
117 type=socket.SOCK_STREAM,
118 proto=0,
119 flags=0)
120 except socket.error as e:
121 self.log('{ex!s}', ex=e)
122 self.next_reconnect = monotonic_time() + self.reconnect_interval
123 return
124
125 # try the next available address
126 a_family, a_type, a_proto, a_canonname, a_sockaddr = self.addrlist[0]
127 del self.addrlist[0]
128
129 self.output_channel = self.connection_factory(self, None, a_family, a_type, a_sockaddr)
130 self.output_channel.connect_now()
131
132 def send_position(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate,
133 callsign, squawk, error_est, nstations, anon, modeac):
134 if self.output_channel:
135 self.output_channel.send_position(timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate,
136 callsign, squawk, error_est, nstations, anon, modeac)
137
138 def heartbeat(self, now):
139 if self.output_channel:
140 self.output_channel.heartbeat(now)
141 elif now > self.next_reconnect:
142 self.reconnect()
143
144 def disconnect(self, reason=None):
145 if self.output_channel:
146 self.output_channel.close()
147
148 def connection_lost(self, child):
149 if self.output_channel is child:
150 self.output_channel = None
151 self.next_reconnect = monotonic_time() + self.reconnect_interval
152
153
154 def format_time(timestamp):
155 return time.strftime("%H:%M:%S", time.gmtime(timestamp)) + ".{0:03.0f}".format(math.modf(timestamp)[0] * 1000)
156
157
158 def format_date(timestamp):
159 return time.strftime("%Y/%m/%d", time.gmtime(timestamp))
160
161
162 def csv_quote(s):
163 if s is None:
164 return ''
165 if s.find('\n') == -1 and s.find('"') == -1 and s.find(',') == -1:
166 return s
167 else:
168 return '"' + s.replace('"', '""') + '"'
169
170
171 class BasicConnection(LoggingMixin, asyncore.dispatcher):
172 def __init__(self, listener, socket, s_family, s_type, addr):
173 super().__init__(sock=socket)
174 self.listener = listener
175 self.s_family = s_family
176 self.s_type = s_type
177 self.addr = addr
178 self.writebuf = bytearray()
179
180 @staticmethod
181 def describe():
182 return 'Basic connection'
183
184 def log(self, fmt, *args, **kwargs):
185 log('{what} with {addr[0]}:{addr[1]}: ' + fmt, *args, what=self.describe(), addr=self.addr, **kwargs)
186
187 def readable(self):
188 return True
189
190 def handle_connect(self):
191 self.log('connection established')
192
193 def handle_read(self):
194 try:
195 self.recv(1024) # discarded
196 except socket.error as e:
197 self.log('{ex!s}', ex=e)
198 self.close()
199
200 def writable(self):
201 return self.connecting or self.writebuf
202
203 def handle_write(self):
204 try:
205 sent = super().send(self.writebuf)
206 del self.writebuf[0:sent]
207 except socket.error as e:
208 if e.errno == errno.EAGAIN:
209 return
210 self.log('{ex!s}', ex=e)
211 self.close()
212
213 def handle_close(self):
214 if self.connected:
215 self.log('connection lost')
216 self.close()
217
218 def close(self):
219 try:
220 super().close()
221 except AttributeError:
222 # blarg, try to eat asyncore bugs
223 pass
224
225 self.listener.connection_lost(self)
226
227 def handle_error(self):
228 t, v, tb = sys.exc_info()
229 self.log('{ex!s}', ex=v)
230 self.handle_close()
231
232 def connect_now(self):
233 if self.socket:
234 return
235
236 try:
237 self.create_socket(self.s_family, self.s_type)
238 self.connect(self.addr)
239 except socket.error as e:
240 self.log('{ex!s}', ex=e)
241 self.close()
242
243 def send(self, data):
244 self.writebuf.extend(data)
245
246
247 class BasestationConnection(BasicConnection):
248 heartbeat_interval = 30.0
249 template = 'MSG,3,1,1,{addrtype}{addr:06X},1,{rcv_date},{rcv_time},{now_date},{now_time},{callsign},{altitude},{speed},{heading},{lat},{lon},{vrate},{squawk},{fs},{emerg},{ident},{aog}' # noqa
250
251 def __init__(self, listener, socket, s_family, s_type, addr):
252 super().__init__(listener, socket, s_family, s_type, addr)
253 self.next_heartbeat = monotonic_time() + self.heartbeat_interval
254
255 @staticmethod
256 def describe():
257 return 'Basestation-format results connection'
258
259 def heartbeat(self, now):
260 if now > self.next_heartbeat:
261 self.next_heartbeat = now + self.heartbeat_interval
262 try:
263 self.send('\n'.encode('ascii'))
264 except socket.error:
265 self.handle_error()
266
267 def send_position(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate,
268 callsign, squawk, error_est, nstations, anon, modeac):
269 if not self.connected:
270 return
271
272 now = time.time()
273 if timestamp is None:
274 timestamp = now
275
276 if nsvel is not None and ewvel is not None:
277 speed = math.sqrt(nsvel ** 2 + ewvel ** 2)
278 heading = math.degrees(math.atan2(ewvel, nsvel))
279 if heading < 0:
280 heading += 360
281 else:
282 speed = None
283 heading = None
284
285 if modeac:
286 addrtype = '@'
287 elif anon:
288 addrtype = '~'
289 else:
290 addrtype = ''
291
292 line = self.template.format(addr=addr,
293 addrtype=addrtype,
294 rcv_date=format_date(timestamp),
295 rcv_time=format_time(timestamp),
296 now_date=format_date(now),
297 now_time=format_time(now),
298 callsign=csv_quote(callsign) if callsign else '',
299 altitude=int(alt),
300 speed=int(speed) if (speed is not None) else '',
301 heading=int(heading) if (heading is not None) else '',
302 lat=round(lat, 4),
303 lon=round(lon, 4),
304 vrate=int(vrate) if (vrate is not None) else '',
305 squawk=csv_quote(squawk) if (squawk is not None) else '',
306 fs='',
307 emerg='',
308 ident='',
309 aog='',
310 error_est=round(error_est, 0) if (error_est is not None) else '',
311 nstations=nstations if (nstations is not None) else '')
312
313 self.send((line + '\n').encode('ascii'))
314 self.next_heartbeat = monotonic_time() + self.heartbeat_interval
315
316
317 class ExtBasestationConnection(BasestationConnection):
318 template = 'MLAT,3,1,1,{addrtype}{addr:06X},1,{rcv_date},{rcv_time},{now_date},{now_time},{callsign},{altitude},{speed},{heading},{lat},{lon},{vrate},{squawk},{fs},{emerg},{ident},{aog},{nstations},,{error_est}' # noqa
319
320 @staticmethod
321 def describe():
322 return 'Extended Basestation-format results connection'
323
324
325 class BeastConnection(BasicConnection):
326 heartbeat_interval = 30.0
327
328 @staticmethod
329 def describe():
330 return 'Beast-format results connection'
331
332 def __init__(self, listener, socket, s_family, s_type, addr):
333 super().__init__(listener, socket, s_family, s_type, addr)
334 self.writebuf = bytearray()
335 self.last_write = monotonic_time()
336
337 def heartbeat(self, now):
338 if (now - self.last_write) > 30.0:
339 # write a keepalive frame
340 self.send(b'\x1A1\x00\x00\x00\x00\x00\x00\x00\x00\x00')
341 self.last_write = now
342
343 def send_frame(self, frame):
344 """Send a 14-byte message in the Beast binary format, using the magic mlat timestamp"""
345
346 # format:
347 # 1A '3' long frame follows
348 # FF 00 'MLAT' 6-byte timestamp, this is the magic MLAT timestamp
349 # 00 signal level
350 # ... 14 bytes of frame data, with 1A bytes doubled
351
352 self.writebuf.extend(b'\x1A3\xFF\x00MLAT\x00')
353 if b'\x1a' not in frame:
354 self.writebuf.extend(frame)
355 else:
356 for b in frame:
357 if b == 0x1A:
358 self.writebuf.append(b)
359 self.writebuf.append(b)
360
361 self.last_write = monotonic_time()
362
363 def send_position(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate,
364 callsign, squawk, error_est, nstations, anon, modeac):
365 if not self.connected:
366 return
367
368 if modeac:
369 df = DF18TRACK
370 elif anon:
371 df = DF18ANON
372 else:
373 df = DF18
374
375 if lat is None or lon is None:
376 if alt is not None:
377 self.send_frame(make_altitude_only_frame(addr, alt, df=df))
378 else:
379 even, odd = make_position_frame_pair(addr, lat, lon, alt, df=df)
380 self.send_frame(even)
381 self.send_frame(odd)
382
383 if nsvel is not None or ewvel is not None or vrate is not None:
384 self.send_frame(make_velocity_frame(addr, nsvel, ewvel, vrate, df=df))