mlat-client-adsbfi/0000755000175100017510000000000014702222416013745 5ustar debiandebianmlat-client-adsbfi/modes_message.c0000644000175100017510000005152614702220435016734 0ustar debiandebian/* * Part of mlat-client - an ADS-B multilateration client. * Copyright 2015, Oliver Jowett * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "_modes.h" /* methods / type behaviour */ static PyObject *modesmessage_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static void modesmessage_dealloc(modesmessage *self); static int modesmessage_init(modesmessage *self, PyObject *args, PyObject *kwds); static int modesmessage_bf_getbuffer(PyObject *self, Py_buffer *view, int flags); static Py_ssize_t modesmessage_sq_length(modesmessage *self); static PyObject *modesmessage_sq_item(modesmessage *self, Py_ssize_t i); static long modesmessage_hash(PyObject *self); static PyObject *modesmessage_richcompare(PyObject *self, PyObject *other, int op); static PyObject *modesmessage_repr(PyObject *self); static PyObject *modesmessage_str(PyObject *self); /* internal helpers */ static PyObject *decode_ac13(unsigned ac13); static uint32_t crc_residual(uint8_t *message, int len); static int decode(modesmessage *self); /* modesmessage fields */ /* todo: these can probably all be read/write */ static PyMemberDef modesmessageMembers[] = { { "timestamp", T_ULONGLONG, offsetof(modesmessage, timestamp), 0, "12MHz timestamp" }, /* read/write */ { "signal", T_UINT, offsetof(modesmessage, signal), READONLY, "signal level" }, { "df", T_UINT, offsetof(modesmessage, df), READONLY, "downlink format or a special DF_* value" }, { "nuc", T_UINT, offsetof(modesmessage, nuc), READONLY, "NUCp value" }, { "even_cpr", T_BOOL, offsetof(modesmessage, even_cpr), READONLY, "CPR even-format flag" }, { "odd_cpr", T_BOOL, offsetof(modesmessage, odd_cpr), READONLY, "CPR odd-format flag" }, { "valid", T_BOOL, offsetof(modesmessage, valid), READONLY, "Does the message look OK?" }, { "crc_residual", T_OBJECT, offsetof(modesmessage, crc), READONLY, "CRC residual" }, { "address", T_OBJECT, offsetof(modesmessage, address), READONLY, "ICAO address" }, { "altitude", T_OBJECT, offsetof(modesmessage, altitude), READONLY, "altitude" }, { "eventdata", T_OBJECT, offsetof(modesmessage, eventdata), READONLY, "event data dictionary for special event messages" }, { NULL, 0, 0, 0, NULL } }; /* modesmessage buffer protocol */ static PyBufferProcs modesmessageBufferProcs = { modesmessage_bf_getbuffer, /* bf_getbuffer */ NULL /* bf_releasebuffer */ }; /* modesmessage sequence protocol */ static PySequenceMethods modesmessageSequenceMethods = { (lenfunc)modesmessage_sq_length, /* sq_length */ 0, /* sq_concat */ 0, /* sq_repeat */ (ssizeargfunc)modesmessage_sq_item, /* sq_item */ 0, /* sq_ass_item */ 0, /* sq_contains */ 0, /* sq_inplace_concat */ 0, /* sq_inplace_repeat */ }; /* modesmessage type object */ static PyTypeObject modesmessageType = { PyVarObject_HEAD_INIT(NULL, 0) "_modes.Message", /* tp_name */ sizeof(modesmessage), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)modesmessage_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ (reprfunc)modesmessage_repr, /* tp_repr */ 0, /* tp_as_number */ &modesmessageSequenceMethods, /* tp_as_sequence */ 0, /* tp_as_mapping */ (hashfunc)modesmessage_hash, /* tp_hash */ 0, /* tp_call */ (reprfunc)modesmessage_str, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ &modesmessageBufferProcs, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT||Py_TPFLAGS_BASETYPE, /* tp_flags */ "A ModeS message.", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ modesmessage_richcompare, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ 0, /* tp_methods */ modesmessageMembers, /* tp_members */ 0, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)modesmessage_init, /* tp_init */ 0, /* tp_alloc */ modesmessage_new, /* tp_new */ }; /* * module setup */ int modesmessage_module_init(PyObject *m) { if (PyType_Ready(&modesmessageType) < 0) return -1; Py_INCREF(&modesmessageType); if (PyModule_AddObject(m, "Message", (PyObject *)&modesmessageType) < 0) { Py_DECREF(&modesmessageType); return -1; } /* Add DF_* constants */ if (PyModule_AddIntMacro(m, DF_MODEAC) < 0) return -1; if (PyModule_AddIntMacro(m, DF_EVENT_TIMESTAMP_JUMP) < 0) return -1; if (PyModule_AddIntMacro(m, DF_EVENT_MODE_CHANGE) < 0) return -1; if (PyModule_AddIntMacro(m, DF_EVENT_EPOCH_ROLLOVER) < 0) return -1; if (PyModule_AddIntMacro(m, DF_EVENT_RADARCAPE_STATUS) < 0) return -1; if (PyModule_AddIntMacro(m, DF_EVENT_RADARCAPE_POSITION) < 0) return -1; return 0; } void modesmessage_module_free(PyObject *m) { } static PyObject *modesmessage_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { modesmessage *self; self = (modesmessage *)type->tp_alloc(type, 0); if (!self) return NULL; /* minimal init */ self->timestamp = 0; self->signal = 0; self->df = 0; self->nuc = 0; self->even_cpr = self->odd_cpr = 0; self->valid = 0; self->crc = NULL; self->address = NULL; self->altitude = NULL; self->data = NULL; self->datalen = 0; self->eventdata = NULL; return (PyObject *)self; } static void modesmessage_dealloc(modesmessage *self) { Py_XDECREF(self->crc); Py_XDECREF(self->address); Py_XDECREF(self->altitude); Py_XDECREF(self->eventdata); free(self->data); Py_TYPE(self)->tp_free((PyObject*)self); } /* internal entry point to build a new message from a buffer */ PyObject *modesmessage_from_buffer(unsigned long long timestamp, unsigned signal, uint8_t *data, int datalen) { modesmessage *message; uint8_t *copydata; if (! (message = (modesmessage*)modesmessage_new(&modesmessageType, NULL, NULL))) goto err; /* minimal init so deallocation works */ message->data = NULL; copydata = malloc(datalen); if (!copydata) { PyErr_NoMemory(); goto err; } memcpy(copydata, data, datalen); message->timestamp = timestamp; message->signal = signal; message->data = copydata; message->datalen = datalen; if (decode(message) < 0) goto err; return (PyObject*)message; err: Py_XDECREF(message); return NULL; } /* internal entry point to build a new event message * steals a reference from eventdata */ PyObject *modesmessage_new_eventmessage(int type, unsigned long long timestamp, PyObject *eventdata) { modesmessage *message; if (! (message = (modesmessage*)modesmessage_new(&modesmessageType, NULL, NULL))) return NULL; message->df = type; message->timestamp = timestamp; message->eventdata = eventdata; return (PyObject *)message; } /* external entry point to build a new event message from python i.e. _modes.EventMessage(...) */ PyObject *modesmessage_eventmessage(PyObject *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "type", "timestamp", "eventdata", NULL }; int type; unsigned long long timestamp; PyObject *eventdata = NULL; PyObject *rv = NULL; if (!PyArg_ParseTupleAndKeywords(args, kwds, "iKO", kwlist, &type, ×tamp, &eventdata)) return NULL; Py_INCREF(eventdata); if (! (rv = modesmessage_new_eventmessage(type, timestamp, eventdata))) { Py_DECREF(eventdata); return NULL; } return rv; } /* external entry point to build a new message from python (i.e. _modes.Message(...)) */ static int modesmessage_init(modesmessage *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "data", "timestamp", "signal", NULL }; Py_buffer data; int rv = -1; if (!PyArg_ParseTupleAndKeywords(args, kwds, "s*|KI", kwlist, &data, &self->timestamp, &self->signal)) return -1; if (data.itemsize != 1) { PyErr_SetString(PyExc_ValueError, "buffer itemsize is not 1"); goto out; } if (!PyBuffer_IsContiguous(&data, 'C')) { PyErr_SetString(PyExc_ValueError, "buffer is not contiguous"); goto out; } self->datalen = 0; free(self->data); self->data = malloc(data.len); if (!self->data) { PyErr_NoMemory(); goto out; } memcpy(self->data, data.buf, data.len); self->datalen = data.len; rv = decode(self); out: PyBuffer_Release(&data); return rv; } static PyObject *decode_ac13(unsigned ac13) { int h, f, a; if (ac13 == 0) Py_RETURN_NONE; if (ac13 & 0x0040) /* M bit */ Py_RETURN_NONE; if (ac13 & 0x0010) { /* Q bit */ int n = ((ac13 & 0x1f80) >> 2) | ((ac13 & 0x0020) >> 1) | (ac13 & 0x000f); return PyLong_FromLong(n * 25 - 1000); } /* convert from Gillham code */ if (! ((ac13 & 0x1500))) { /* illegal gillham code */ Py_RETURN_NONE; } h = 0; if (ac13 & 0x1000) h ^= 7; /* C1 */ if (ac13 & 0x0400) h ^= 3; /* C2 */ if (ac13 & 0x0100) h ^= 1; /* C4 */ if (h & 5) h ^= 5; if (h > 5) Py_RETURN_NONE; /* illegal */ f = 0; if (ac13 & 0x0010) f ^= 0x1ff; /* D1 */ if (ac13 & 0x0004) f ^= 0x0ff; /* D2 */ if (ac13 & 0x0001) f ^= 0x07f; /* D4 */ if (ac13 & 0x0800) f ^= 0x03f; /* A1 */ if (ac13 & 0x0200) f ^= 0x01f; /* A2 */ if (ac13 & 0x0080) f ^= 0x00f; /* A4 */ if (ac13 & 0x0020) f ^= 0x007; /* B1 */ if (ac13 & 0x0008) f ^= 0x003; /* B2 */ if (ac13 & 0x0002) f ^= 0x001; /* B4 */ if (f & 1) h = (6 - h); a = 500 * f + 100 * h - 1300; if (a < -1200) Py_RETURN_NONE; /* illegal */ return PyLong_FromLong(a); } static PyObject *decode_ac12(unsigned ac12) { return decode_ac13(((ac12 & 0x0fc0) << 1) | (ac12 & 0x003f)); } static uint32_t crc_residual(uint8_t *message, int len) { uint32_t crc; if (len < 3) return 0; crc = modescrc_buffer_crc(message, len - 3); crc = crc ^ (message[len-3] << 16); crc = crc ^ (message[len-2] << 8); crc = crc ^ (message[len-1]); return crc; } static int decode(modesmessage *self) { uint32_t crc; /* clear state */ self->valid = 0; self->nuc = 0; self->odd_cpr = self->even_cpr = 0; Py_CLEAR(self->crc); Py_CLEAR(self->address); Py_CLEAR(self->altitude); if (self->datalen == 2) { self->df = DF_MODEAC; self->address = PyLong_FromLong((self->data[0] << 8) | self->data[1]); self->valid = 1; return 0; } self->df = (self->data[0] >> 3) & 31; if ((self->df < 16 && self->datalen != 7) || (self->df >= 16 && self->datalen != 14)) { /* wrong length, no further processing */ return 0; } if (self->df != 0 && self->df != 4 && self->df != 5 && self->df != 11 && self->df != 16 && self->df != 17 && self->df != 20 && self->df != 21) { /* we do not know how to handle this message type, no further processing */ return 0; } crc = crc_residual(self->data, self->datalen); if (!(self->crc = PyLong_FromLong(crc))) return -1; switch (self->df) { case 0: case 4: case 16: case 20: self->address = (Py_INCREF(self->crc), self->crc); if (! (self->altitude = decode_ac13((self->data[2] & 0x1f) << 8 | (self->data[3])))) return -1; self->valid = 1; break; case 5: case 21: case 24: self->address = (Py_INCREF(self->crc), self->crc); self->valid = 1; break; case 11: self->valid = ((crc & ~0x7f) == 0); if (self->valid) { if (! (self->address = PyLong_FromLong( (self->data[1] << 16) | (self->data[2] << 8) | (self->data[3]) ))) return -1; } break; case 17: self->valid = (crc == 0); if (self->valid) { unsigned metype; unsigned address = (self->data[1] << 16) | (self->data[2] << 8) | (self->data[3]); self->address = PyLong_FromLong(address); if (!self->address) return -1; metype = self->data[4] >> 3; if ((metype >= 9 && metype <= 18) || (metype >= 20 && metype < 22)) { if (metype == 22) self->nuc = 0; else if (metype <= 18) self->nuc = 18 - metype; else self->nuc = 29 - metype; if (0 && self->nuc <= 5) { fprintf(stderr, "%06x nuc: %d\n", address, self->nuc); } if (self->data[6] & 0x04) self->odd_cpr = 1; else self->even_cpr = 1; if (! (self->altitude = decode_ac12((self->data[5] << 4) | ((self->data[6] & 0xF0) >> 4)))) return -1; // crude check if there is any CPR data, if either cpr_lat or cpr_lon is mostly zeros, set invalid if ((self->data[7] == 0 && (self->data[8] & 0x7F) == 0) || (self->data[9] == 0 && self->data[10] == 0)) { self->valid = 0; if (0) { fprintf(stderr, "%06x %02x %02x %02x %02x\n", address, self->data[7], self->data[8], self->data[9], self->data[10]); } } } } break; default: break; } return 0; } static int modesmessage_bf_getbuffer(PyObject *self, Py_buffer *view, int flags) { return PyBuffer_FillInfo(view, self, ((modesmessage*)self)->data, ((modesmessage*)self)->datalen, 1, flags); } static Py_ssize_t modesmessage_sq_length(modesmessage *self) { return self->datalen; } static PyObject *modesmessage_sq_item(modesmessage *self, Py_ssize_t i) { if (i < 0 || i >= self->datalen) { PyErr_SetString(PyExc_IndexError, "byte index out of range"); return NULL; } return PyLong_FromLong(self->data[i]); } static long modesmessage_hash(PyObject *self) { modesmessage *msg = (modesmessage*)self; uint32_t hash = 0; int i; /* Jenkins one-at-a-time hash */ for (i = 0; i < 4 && i < msg->datalen; ++i) { hash += msg->data[i] & 0xff; hash += hash << 10; hash ^= hash >> 6; } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return (long)hash; } static PyObject *modesmessage_richcompare(PyObject *self, PyObject *other, int op) { PyObject *result = NULL; if (! PyObject_TypeCheck(self, &modesmessageType) || ! PyObject_TypeCheck(other, &modesmessageType)) { result = Py_NotImplemented; } else { modesmessage *message1 = (modesmessage*)self; modesmessage *message2 = (modesmessage*)other; int c = 0; switch (op) { case Py_EQ: c = (message1->datalen == message2->datalen) && (memcmp(message1->data, message2->data, message1->datalen) == 0); break; case Py_NE: c = (message1->datalen != message2->datalen) || (memcmp(message1->data, message2->data, message1->datalen) != 0); break; case Py_LT: c = (message1->datalen < message2->datalen) || (message1->datalen == message2->datalen && memcmp(message1->data, message2->data, message1->datalen) < 0); break; case Py_LE: c = (message1->datalen < message2->datalen) || (message1->datalen == message2->datalen && memcmp(message1->data, message2->data, message1->datalen) <= 0); break; case Py_GT: c = (message1->datalen > message2->datalen) || (message1->datalen == message2->datalen && memcmp(message1->data, message2->data, message1->datalen) > 0); break; case Py_GE: c = (message1->datalen > message2->datalen) || (message1->datalen == message2->datalen && memcmp(message1->data, message2->data, message1->datalen) >= 0); break; default: result = Py_NotImplemented; break; } if (!result) result = (c ? Py_True : Py_False); } Py_INCREF(result); return result; } static const char *df_event_name(int df) { switch (df) { case DF_EVENT_TIMESTAMP_JUMP: return "DF_EVENT_TIMESTAMP_JUMP"; case DF_EVENT_MODE_CHANGE: return "DF_EVENT_MODE_CHANGE"; case DF_EVENT_EPOCH_ROLLOVER: return "DF_EVENT_EPOCH_ROLLOVER"; case DF_EVENT_RADARCAPE_STATUS: return "DF_EVENT_RADARCAPE_STATUS"; default: return NULL; } } static char hexdigit[16] = "0123456789abcdef"; static PyObject *modesmessage_repr(PyObject *self) { modesmessage *message = (modesmessage *)self; if (message->data) { char buf[256]; char *p = buf; int i; for (i = 0; i < message->datalen; ++i) { *p++ = '\\'; *p++ = 'x'; *p++ = hexdigit[(message->data[i] >> 4) & 15]; *p++ = hexdigit[message->data[i] & 15]; } *p++ = 0; return PyUnicode_FromFormat("_modes.Message(b'%s',%llu,%u)", buf, (unsigned long long)message->timestamp, (unsigned)message->signal); } else { const char *eventname = df_event_name(message->df); if (eventname) { return PyUnicode_FromFormat("_modes.EventMessage(_modes.%s,%llu,%R)", df_event_name(message->df), (unsigned long long)message->timestamp, message->eventdata); } else { return PyUnicode_FromFormat("_modes.EventMessage(%d,%llu,%R)", message->df, (unsigned long long)message->timestamp, message->eventdata); } } } static PyObject *modesmessage_str(PyObject *self) { modesmessage *message = (modesmessage *)self; if (message->data) { char buf[256]; char *p = buf; int i; for (i = 0; i < message->datalen; ++i) { *p++ = hexdigit[(message->data[i] >> 4) & 15]; *p++ = hexdigit[message->data[i] & 15]; } *p++ = 0; return PyUnicode_FromString(buf); } else { const char *eventname = df_event_name(message->df); if (eventname) { return PyUnicode_FromFormat("%s@%llu:%R", eventname, (unsigned long long)message->timestamp, message->eventdata); } else { return PyUnicode_FromFormat("DF%d@%llu:%R", message->df, (unsigned long long)message->timestamp, message->eventdata); } } } mlat-client-adsbfi/modes_crc.c0000644000175100017510000000432614702220435016053 0ustar debiandebian/* * Part of mlat-client - an ADS-B multilateration client. * Copyright 2015, Oliver Jowett * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "_modes.h" /********** CRC ****************/ /* Generator polynomial for the Mode S CRC */ #define MODES_GENERATOR_POLY 0xfff409U /* CRC values for all single-byte messages; used to speed up CRC calculation. */ static uint32_t crc_table[256]; int modescrc_module_init(PyObject *m) { int i; for (i = 0; i < 256; ++i) { uint32_t c = i << 16; int j; for (j = 0; j < 8; ++j) { if (c & 0x800000) c = (c<<1) ^ MODES_GENERATOR_POLY; else c = (c<<1); } crc_table[i] = c & 0x00ffffff; } return 0; } void modescrc_module_free(PyObject *m) { } uint32_t modescrc_buffer_crc(uint8_t *buf, Py_ssize_t len) { uint32_t rem; Py_ssize_t i; for (rem = 0, i = len; i > 0; --i) { rem = ((rem & 0x00ffff) << 8) ^ crc_table[*buf++ ^ ((rem & 0xff0000) >> 16)]; } return rem; } PyObject *modescrc_crc(PyObject *self, PyObject *args) { Py_buffer buffer; PyObject *rv = NULL; if (!PyArg_ParseTuple(args, "s*", &buffer)) return NULL; if (buffer.itemsize != 1) { PyErr_SetString(PyExc_ValueError, "buffer itemsize is not 1"); goto out; } if (!PyBuffer_IsContiguous(&buffer, 'C')) { PyErr_SetString(PyExc_ValueError, "buffer is not contiguous"); goto out; } rv = PyLong_FromLong(modescrc_buffer_crc(buffer.buf, buffer.len)); out: PyBuffer_Release(&buffer); return rv; } mlat-client-adsbfi/mlat-client0000755000175100017510000001354614702220435016114 0ustar debiandebian#!/usr/bin/env python3 # -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import argparse import mlat.client.version import time from mlat.client import util from mlat.client.receiver import ReceiverConnection from mlat.client.jsonclient import JsonServerConnection from mlat.client.coordinator import Coordinator from mlat.client import options def main(): parser = argparse.ArgumentParser(description="Client for multilateration.") options.make_inputs_group(parser) options.make_results_group(parser) location = parser.add_argument_group('Receiver location') location.add_argument('--lat', type=options.latitude, help="Latitude of the receiver, in decimal degrees. Required.", required=True) location.add_argument('--lon', type=options.longitude, help="Longitude of the receiver, in decimal degrees. Required.", required=True) location.add_argument('--alt', type=options.altitude, help=""" Altitude of the receiver (height above ellipsoid). Required. Defaults to metres, but units may specified with a 'ft' or 'm' suffix. (Except if they're negative due to option parser weirdness. Sorry!)""", required=True) location.add_argument('--privacy', help=""" Sets the privacy flag for this receiver. Currently, this removes the receiver location pin from the coverage maps.""", action='store_true', default=False) server = parser.add_argument_group('Multilateration server connection') server.add_argument('--user', help="User information to give to the server. Used to get in touch if there are problems.", required=True) server.add_argument('--server', help="host:port of the multilateration server to connect to", type=options.hostport, default=('feed.adsb.fi', 31090)) server.add_argument('--no-udp', dest='udp', help="Don't offer to use UDP transport for sync/mlat messages", action='store_false', default=True) server.add_argument('--uuid-file', dest='uuid_path', help="Send the UUID in this file to the server", required=False) server.add_argument('--uuid', dest='uuid', help="Send this UUID to the server", required=False) logOptions = parser.add_argument_group('Log Options') logOptions.add_argument('--log-timestamps', dest='log_timestamps', help="Print timestamps in logging output", action='store_true', default=False) args = parser.parse_args() util.suppress_log_timestamps = not args.log_timestamps if abs(args.lat) < 0.1 and abs(args.lon) < 0.1: util.log("<3>Latitude / Longitude not set, please configure and reboot") time.sleep(3600) raise SystemExit util.log("mlat-client {version} starting up", version=mlat.client.version.CLIENT_VERSION) outputs = options.build_outputs(args) receiver = ReceiverConnection(host=args.input_connect[0], port=args.input_connect[1], mode=options.connection_mode(args)) uuid_path = None uuid = None if args.uuid is not None: uuid = [ args.uuid ] if args.uuid_path is not None: uuid_path = [ args.uuid_path ] else: uuid_path = [ '/usr/local/share/adsbfi/adsbfi-uuid', '/boot/adsbfi-uuid' ] server = JsonServerConnection(host=args.server[0], port=args.server[1], uuid_path=uuid_path, uuid=uuid, handshake_data={'lat': args.lat, 'lon': args.lon, 'alt': args.alt, 'user': args.user, 'clock_type': options.clock_type(args), 'clock_frequency': options.clock_frequency(args), 'clock_epoch': options.clock_epoch(args), 'privacy': args.privacy}, offer_zlib=True, offer_udp=args.udp, return_results=(len(outputs) > 0)) coordinator = Coordinator(receiver=receiver, server=server, outputs=outputs, freq=options.clock_frequency(args), allow_anon=args.allow_anon_results, allow_modeac=args.allow_modeac_results) server.start() coordinator.run_forever() if __name__ == '__main__': main() mlat-client-adsbfi/_modes.h0000644000175100017510000000455114702220435015370 0ustar debiandebian#ifndef _MODES_H #define _MODES_H /* * Part of mlat-client - an ADS-B multilateration client. * Copyright 2015, Oliver Jowett * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include /* a modesmessage object */ typedef struct { PyObject_HEAD unsigned long long timestamp; unsigned int signal; unsigned int df; unsigned int nuc; char even_cpr; char odd_cpr; char valid; PyObject *crc; PyObject *address; PyObject *altitude; uint8_t *data; int datalen; PyObject *eventdata; } modesmessage; /* special DF types for non-Mode-S messages */ #define DF_MODEAC 32 #define DF_EVENT_TIMESTAMP_JUMP 33 #define DF_EVENT_MODE_CHANGE 34 #define DF_EVENT_EPOCH_ROLLOVER 35 #define DF_EVENT_RADARCAPE_STATUS 36 #define DF_EVENT_RADARCAPE_POSITION 37 /* factory function to build a modesmessage from a provided buffer */ PyObject *modesmessage_from_buffer(unsigned long long timestamp, unsigned signal, uint8_t *data, int datalen); /* factory function to build an event message */ PyObject *modesmessage_new_eventmessage(int type, unsigned long long timestamp, PyObject *eventdata); /* python entry point */ PyObject *modesmessage_eventmessage(PyObject *self, PyObject *args, PyObject *kwds); /* crc helpers */ uint32_t modescrc_buffer_crc(uint8_t *buf, Py_ssize_t len); /* internal interface */ PyObject *modescrc_crc(PyObject *self, PyObject *args); /* external interface */ /* submodule init/cleanup */ int modescrc_module_init(PyObject *m); void modescrc_module_free(PyObject *m); int modesreader_module_init(PyObject *m); void modesreader_module_free(PyObject *m); int modesmessage_module_init(PyObject *m); void modesmessage_module_free(PyObject *m); #endif mlat-client-adsbfi/fa-mlat-client0000755000175100017510000000414614702220435016474 0ustar debiandebian#!/usr/bin/env python3 # -*- mode: python; indent-tabs-mode: nil -*- # FlightAware multilateration client import argparse import mlat.client.version from flightaware.client.adeptclient import AdeptConnection, UdpServerConnection from mlat.client.coordinator import Coordinator from mlat.client.util import log, log_exc from mlat.client import options def main(): # piaware will timestamp our log messages itself, suppress the normal logging timestamps mlat.client.util.suppress_log_timestamps = True parser = argparse.ArgumentParser(description="Client for multilateration.") options.make_inputs_group(parser) options.make_results_group(parser) parser.add_argument('--udp-transport', help="Provide UDP transport information. Expects an IP:port:key argument.", required=True) args = parser.parse_args() log("fa-mlat-client {version} starting up", version=mlat.client.version.CLIENT_VERSION) # udp_transport is IP:port:key # split backwards to handle IPv6 addresses in the host part, which themselves contain colons. parts = args.udp_transport.split(':') udp_key = int(parts[-1]) udp_port = int(parts[-2]) udp_host = ':'.join(parts[:-2]) udp_transport = UdpServerConnection(udp_host, udp_port, udp_key) log("Using UDP transport to {host} port {port}", host=udp_host, port=udp_port) receiver = options.build_receiver_connection(args) adept = AdeptConnection(udp_transport, allow_anon=args.allow_anon_results, allow_modeac=args.allow_modeac_results) outputs = options.build_outputs(args) coordinator = Coordinator(receiver=receiver, server=adept, outputs=outputs, freq=options.clock_frequency(args), allow_anon=args.allow_anon_results, allow_modeac=args.allow_modeac_results) adept.start(coordinator) coordinator.run_until(lambda: adept.closed) if __name__ == '__main__': try: main() except KeyboardInterrupt: log("Exiting on SIGINT") except Exception: log_exc("Exiting on exception") else: log("Exiting on connection loss") mlat-client-adsbfi/README.md0000644000175100017510000000441014702220435015222 0ustar debiandebian# mlat-client This is a client that selectively forwards Mode S messages to a server that resolves the transmitter position by multilateration of the same message received by multiple clients. The supporting server code is available at https://github.com/adsbfi/mlat-server. ## Building Due to conflicting packages with the same name, it's recommended to install in a Python virtual environment. First set the direcory you'd like to install to, if that path is not writeable by your user, use `sudo su` to become root first. ``` VENV=/usr/local/share/adsbfi-mlat-client/venv ``` Now the build / install, it's not a bad idea to recreate the virtual environment when rebuilding: ``` rm -rf "$VENV" python3 -m venv "$VENV" source "$VENV/bin/activate" python3 setup.py build python3 setup.py install ``` To run it, invoke: ``` /usr/local/share/adsbfi-mlat-client/venv/bin/mlat-client ``` ## Running Used in conjuction with the following scripts https://github.com/adsbfi/adsb-fi-scripts If you are connecting to a third party multilateration server, contact the server's administrator for configuration instructions. ## Supported receivers * Anything that produces Beast-format output with a 12MHz clock: * readsb, dump1090-mutability, dump1090-fa * an actual Mode-S Beast * airspy_adsb in Beast output mode * Radarcape in 12MHz mode * Radarcape in GPS mode ## Unsupported receivers * The FlightRadar24 radarcape-based receiver. This produces a deliberately crippled timestamp in its output, making it useless for multilateration. If you have one of these, you should ask FR24 to fix this. ## Original License Copyright 2015, [Oliver Jowett](mailto:oliver@mutability.co.uk). This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received [a copy of the GNU General Public License](COPYING) along with this program. If not, see . mlat-client-adsbfi/tools/0000755000175100017510000000000014702220435015104 5ustar debiandebianmlat-client-adsbfi/tools/compare-message-timing.py0000755000175100017510000001240414702220435022017 0ustar debiandebian#!/usr/bin/env python3 # build/install the _modes module: # $ python3 ./setup.py install --user # # run the script, passing hostnames for 2 or more receivers: # $ ./compare-message-timing.py host1 host2 # # output should start after around 20 seconds; # the output format is TSV with a pair of columns for each # receiver: time (seconds) and offset from the first receiver time # (nanoseconds) import sys import traceback import asyncio import concurrent.futures import _modes class Receiver(object): def __init__(self, *, loop, id, host, port, correlator): self.loop = loop self.id = id self.host = host self.port = port self.parser = _modes.Reader(_modes.BEAST) self.parser.default_filter = [False] * 32 self.parser.default_filter[17] = True self.frequency = None self.task = asyncio.async(self.handle_connection()) self.correlator = correlator def __str__(self): return 'client #{0} ({1}:{2})'.format(self.id, self.host, self.port) @asyncio.coroutine def handle_connection(self): try: reader, writer = yield from asyncio.open_connection(self.host, self.port) print(self, 'connected', file=sys.stderr) # Binary format, no filters, CRC checks enabled, mode A/C disabled writer.write(b'\x1a1C\x1a1d\x1a1f\x1a1j') self.loop.call_later(5.0, self.set_default_freq) data = b'' while True: moredata = yield from reader.read(4096) if len(moredata) == 0: break data += moredata consumed, messages, pending_error = self.parser.feed(data) data = data[consumed:] self.handle_messages(messages) if pending_error: self.parser.feed(self.data) print(self, 'connection closed', file=sys.stderr) writer.close() except concurrent.futures.CancelledError: pass except Exception: print(self, 'unexpected exception', file=sys.stderr) traceback.print_exc(file=sys.stderr) def set_default_freq(self): if self.frequency is None: print(self, 'assuming 12MHz clock frequency', file=sys.stderr) self.frequency = 12e6 def handle_messages(self, messages): for message in messages: if message.df == _modes.DF_EVENT_MODE_CHANGE: self.frequency = message.eventdata['frequency'] print(self, 'clock frequency changed to {0:.0f}MHz'.format(self.frequency/1e6), file=sys.stderr) elif message.df == 17 and (message.even_cpr or message.odd_cpr) and self.frequency is not None: self.correlator(self.id, self.frequency, message) class Correlator(object): def __init__(self, loop): self.loop = loop self.pending = {} self.clients = set() self.sorted_clients = [] self.base_times = None def add_client(self, client_id): self.clients.add(client_id) self.sorted_clients = sorted(self.clients) def correlate(self, client_id, frequency, message): if message in self.pending: self.pending[message].append((client_id, frequency, message)) else: self.pending[message] = [ (client_id, frequency, message) ] self.loop.call_later(10.0, self.resolve, message) def resolve(self, message): copies = self.pending.pop(message) client_times = {} for client_id, frequency, message_copy in copies: if client_id in client_times: # occurs multiple times, ambiguous, skip it return client_times[client_id] = float(message_copy.timestamp) / frequency if set(client_times.keys()) == self.clients: # all clients saw this message if self.base_times is None: # first matching message, record baseline timestamps self.base_times = client_times line = '' ref_time = client_times[self.sorted_clients[0]] - self.base_times[self.sorted_clients[0]] for client_id in self.sorted_clients: this_time = client_times[client_id] - self.base_times[client_id] offset = this_time - ref_time line += '{t:.9f}\t{o:.0f}\t'.format(t = this_time, o = offset * 1e9) print(line[:-1]) sys.stdout.flush() if __name__ == '__main__': if len(sys.argv) < 3: print('usage: {0} host1 host2 ...'.format(sys.argv[0])) sys.exit(1) loop = asyncio.get_event_loop() correlator = Correlator(loop) clients = [] for i in range(1, len(sys.argv)): client_id = str(i) clients.append(Receiver(loop = loop, id = client_id, host = sys.argv[i], port = 30005, correlator = correlator.correlate)) correlator.add_client(client_id) tasks = [client.task for client in clients] try: done, pending = loop.run_until_complete(asyncio.wait(tasks, return_when = asyncio.FIRST_COMPLETED)) except KeyboardInterrupt: pending = tasks for task in pending: task.cancel() loop.run_until_complete(asyncio.gather(*pending)) loop.close() mlat-client-adsbfi/run-flake8.sh0000755000175100017510000000013514702220435016256 0ustar debiandebian#!/bin/sh D=`dirname $0` flake8 --exclude=.git,__pycache__,build,debian,tools mlat-client $D mlat-client-adsbfi/tox.ini0000644000175100017510000000003514702220435015255 0ustar debiandebian[flake8] max-line-length=120 mlat-client-adsbfi/setup.py0000755000175100017510000000347514702220435015472 0ustar debiandebian#!/usr/bin/env python3 # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys # setuptools with python 3.9 is buggy or something # only use setuptools for 3.10 and up as distutils is deprecated 3.12 and up if sys.version_info.minor >= 10: from setuptools import setup, Extension else: from distutils.core import setup, Extension import platform # get the version from the source CLIENT_VERSION = "unknown" exec(open('mlat/client/version.py').read()) more_warnings = False extra_compile_args = [] if platform.system() == 'Linux': extra_compile_args.append('-O3') if more_warnings: # let's assume this is GCC extra_compile_args.append('-Wpointer-arith') modes_ext = Extension('_modes', sources=['_modes.c', 'modes_reader.c', 'modes_message.c', 'modes_crc.c'], extra_compile_args=extra_compile_args) setup(name='MlatClient', version=CLIENT_VERSION, description='Multilateration client package', author='adsb.fi', author_email='adsb.fi', packages=['mlat', 'mlat.client'], ext_modules=[modes_ext], scripts=['mlat-client']) mlat-client-adsbfi/COPYING0000644000175100017510000010451314702220435015003 0ustar debiandebian GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . mlat-client-adsbfi/mlat/0000755000175100017510000000000014702220435014701 5ustar debiandebianmlat-client-adsbfi/mlat/constants.py0000644000175100017510000000221414702220435017266 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-server: a Mode S multilateration server # Copyright (C) 2015 Oliver Jowett # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Useful constants for unit conversion. """ import math # signal propagation speed in metres per second Cair = 299792458 / 1.0003 # degrees to radians DTOR = math.pi / 180.0 # radians to degrees RTOD = 180.0 / math.pi # feet to metres FTOM = 0.3048 # metres to feet MTOF = 1.0/FTOM # m/s to knots MS_TO_KTS = 1.9438 # m/s to fpm MS_TO_FPM = MTOF * 60 mlat-client-adsbfi/mlat/geodesy.py0000644000175100017510000000602714702220435016717 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-server: a Mode S multilateration server # Copyright (C) 2015 Oliver Jowett # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Utility functions to convert between coordinate systems and calculate distances. """ import math from .constants import DTOR, RTOD # WGS84 ellipsoid Earth parameters WGS84_A = 6378137.0 WGS84_F = 1.0/298.257223563 WGS84_B = WGS84_A * (1 - WGS84_F) WGS84_ECC_SQ = 1 - WGS84_B * WGS84_B / (WGS84_A * WGS84_A) WGS84_ECC = math.sqrt(WGS84_ECC_SQ) # Average radius for a spherical Earth SPHERICAL_R = 6371e3 # Some derived values _wgs84_ep = math.sqrt((WGS84_A**2 - WGS84_B**2) / WGS84_B**2) _wgs84_ep2_b = _wgs84_ep**2 * WGS84_B _wgs84_e2_a = WGS84_ECC_SQ * WGS84_A def llh2ecef(llh): """Converts from WGS84 lat/lon/height to ellipsoid-earth ECEF""" lat = llh[0] * DTOR lng = llh[1] * DTOR alt = llh[2] slat = math.sin(lat) slng = math.sin(lng) clat = math.cos(lat) clng = math.cos(lng) d = math.sqrt(1 - (slat * slat * WGS84_ECC_SQ)) rn = WGS84_A / d x = (rn + alt) * clat * clng y = (rn + alt) * clat * slng z = (rn * (1 - WGS84_ECC_SQ) + alt) * slat return (x, y, z) def ecef2llh(ecef): "Converts from ECEF to WGS84 lat/lon/height" x, y, z = ecef lon = math.atan2(y, x) p = math.sqrt(x**2 + y**2) th = math.atan2(WGS84_A * z, WGS84_B * p) lat = math.atan2(z + _wgs84_ep2_b * math.sin(th)**3, p - _wgs84_e2_a * math.cos(th)**3) N = WGS84_A / math.sqrt(1 - WGS84_ECC_SQ * math.sin(lat)**2) alt = p / math.cos(lat) - N return (lat*RTOD, lon*RTOD, alt) def greatcircle(p0, p1): """Returns a great-circle distance in metres between two LLH points, _assuming spherical earth_ and _ignoring altitude_. Don't use this if you need a distance accurate to better than 1%.""" lat0 = p0[0] * DTOR lon0 = p0[1] * DTOR lat1 = p1[0] * DTOR lon1 = p1[1] * DTOR return SPHERICAL_R * math.acos( math.sin(lat0) * math.sin(lat1) + math.cos(lat0) * math.cos(lat1) * math.cos(abs(lon0 - lon1))) # direct implementation here turns out to be _much_ faster (10-20x) compared to # scipy.spatial.distance.euclidean or numpy-based approaches def ecef_distance(p0, p1): """Returns the straight-line distance in metres between two ECEF points.""" return math.sqrt((p0[0] - p1[0])**2 + (p0[1] - p1[1])**2 + (p0[2] - p1[2])**2) mlat-client-adsbfi/mlat/__init__.py0000644000175100017510000000000014702220435017000 0ustar debiandebianmlat-client-adsbfi/mlat/client/0000755000175100017510000000000014702220435016157 5ustar debiandebianmlat-client-adsbfi/mlat/client/output.py0000644000175100017510000003230414702220435020073 0ustar debiandebian# -*- python -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys import asyncore import socket import time import math import errno from mlat.client.net import LoggingMixin from mlat.client.util import log, monotonic_time from mlat.client.synthetic_es import make_altitude_only_frame, \ make_position_frame_pair, make_velocity_frame, DF18, DF18ANON, DF18TRACK class OutputListener(LoggingMixin, asyncore.dispatcher): def __init__(self, port, connection_factory): asyncore.dispatcher.__init__(self) self.port = port self.a_type = socket.SOCK_STREAM try: # bind to V6 so we can accept both V4 and V6 # (asyncore makes it a hassle to bind to more than # one address here) self.a_family = socket.AF_INET6 self.create_socket(self.a_family, self.a_type) except socket.error: # maybe no v6 support? self.a_family = socket.AF_INET self.create_socket(self.a_family, self.a_type) try: self.set_reuse_addr() self.bind(('', port)) self.listen(5) except Exception: self.close() raise self.output_channels = set() self.connection_factory = connection_factory log('Listening for {0} on port {1}', connection_factory.describe(), port) def handle_accept(self): accepted = self.accept() if not accepted: return new_socket, address = accepted log('Accepted {0} from {1}:{2}', self.connection_factory.describe(), address[0], address[1]) self.output_channels.add(self.connection_factory(self, new_socket, self.a_type, self.a_family, address)) def send_position(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate, callsign, squawk, error_est, nstations, anon, modeac): for channel in list(self.output_channels): channel.send_position(timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate, callsign, squawk, error_est, nstations, anon, modeac) def heartbeat(self, now): for channel in list(self.output_channels): channel.heartbeat(now) def disconnect(self, reason=None): for channel in list(self.output_channels): channel.close() self.close() def connection_lost(self, child): self.output_channels.discard(child) class OutputConnector: reconnect_interval = 30.0 def __init__(self, addr, connection_factory): self.addr = addr self.connection_factory = connection_factory self.output_channel = None self.next_reconnect = monotonic_time() self.addrlist = [] @staticmethod def describe(): return 'OutputConnector' def log(self, fmt, *args, **kwargs): log('{what} with {host}:{port}: ' + fmt, *args, what=self.describe(), host=self.addr[0], port=self.addr[1], **kwargs) def reconnect(self): if len(self.addrlist) == 0: try: self.addrlist = socket.getaddrinfo(host=self.addr[0], port=self.addr[1], family=socket.AF_UNSPEC, type=socket.SOCK_STREAM, proto=0, flags=0) except socket.error as e: self.log('{ex!s}', ex=e) self.next_reconnect = monotonic_time() + self.reconnect_interval return # try the next available address a_family, a_type, a_proto, a_canonname, a_sockaddr = self.addrlist[0] del self.addrlist[0] self.output_channel = self.connection_factory(self, None, a_family, a_type, a_sockaddr) self.output_channel.connect_now() def send_position(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate, callsign, squawk, error_est, nstations, anon, modeac): if self.output_channel: self.output_channel.send_position(timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate, callsign, squawk, error_est, nstations, anon, modeac) def heartbeat(self, now): if self.output_channel: self.output_channel.heartbeat(now) elif now > self.next_reconnect: self.reconnect() def disconnect(self, reason=None): if self.output_channel: self.output_channel.close() def connection_lost(self, child): if self.output_channel is child: self.output_channel = None self.next_reconnect = monotonic_time() + self.reconnect_interval def format_time(timestamp): return time.strftime("%H:%M:%S", time.gmtime(timestamp)) + ".{0:03.0f}".format(math.modf(timestamp)[0] * 1000) def format_date(timestamp): return time.strftime("%Y/%m/%d", time.gmtime(timestamp)) def csv_quote(s): if s is None: return '' if s.find('\n') == -1 and s.find('"') == -1 and s.find(',') == -1: return s else: return '"' + s.replace('"', '""') + '"' class BasicConnection(LoggingMixin, asyncore.dispatcher): def __init__(self, listener, socket, s_family, s_type, addr): super().__init__(sock=socket) self.listener = listener self.s_family = s_family self.s_type = s_type self.addr = addr self.writebuf = bytearray() @staticmethod def describe(): return 'Basic connection' def log(self, fmt, *args, **kwargs): log('{what} with {addr[0]}:{addr[1]}: ' + fmt, *args, what=self.describe(), addr=self.addr, **kwargs) def readable(self): return True def handle_connect(self): self.log('connection established') def handle_read(self): try: self.recv(1024) # discarded except socket.error as e: self.log('{ex!s}', ex=e) self.close() def writable(self): return self.connecting or self.writebuf def handle_write(self): try: sent = super().send(self.writebuf) del self.writebuf[0:sent] except socket.error as e: if e.errno == errno.EAGAIN: return self.log('{ex!s}', ex=e) self.close() def handle_close(self): if self.connected: self.log('connection lost') self.close() def close(self): try: super().close() except AttributeError: # blarg, try to eat asyncore bugs pass self.listener.connection_lost(self) def handle_error(self): t, v, tb = sys.exc_info() self.log('{ex!s}', ex=v) self.handle_close() def connect_now(self): if self.socket: return try: self.create_socket(self.s_family, self.s_type) self.connect(self.addr) except socket.error as e: self.log('{ex!s}', ex=e) self.close() def send(self, data): self.writebuf.extend(data) class BasestationConnection(BasicConnection): heartbeat_interval = 30.0 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 def __init__(self, listener, socket, s_family, s_type, addr): super().__init__(listener, socket, s_family, s_type, addr) self.next_heartbeat = monotonic_time() + self.heartbeat_interval @staticmethod def describe(): return 'Basestation-format results connection' def heartbeat(self, now): if now > self.next_heartbeat: self.next_heartbeat = now + self.heartbeat_interval try: self.send('\n'.encode('ascii')) except socket.error: self.handle_error() def send_position(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate, callsign, squawk, error_est, nstations, anon, modeac): if not self.connected: return now = time.time() if timestamp is None: timestamp = now if nsvel is not None and ewvel is not None: speed = math.sqrt(nsvel ** 2 + ewvel ** 2) heading = math.degrees(math.atan2(ewvel, nsvel)) if heading < 0: heading += 360 else: speed = None heading = None if modeac: addrtype = '@' elif anon: addrtype = '~' else: addrtype = '' line = self.template.format(addr=addr, addrtype=addrtype, rcv_date=format_date(timestamp), rcv_time=format_time(timestamp), now_date=format_date(now), now_time=format_time(now), callsign=csv_quote(callsign) if callsign else '', altitude=int(alt), speed=int(speed) if (speed is not None) else '', heading=int(heading) if (heading is not None) else '', lat=round(lat, 4), lon=round(lon, 4), vrate=int(vrate) if (vrate is not None) else '', squawk=csv_quote(squawk) if (squawk is not None) else '', fs='', emerg='', ident='', aog='', error_est=round(error_est, 0) if (error_est is not None) else '', nstations=nstations if (nstations is not None) else '') self.send((line + '\n').encode('ascii')) self.next_heartbeat = monotonic_time() + self.heartbeat_interval class ExtBasestationConnection(BasestationConnection): 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 @staticmethod def describe(): return 'Extended Basestation-format results connection' class BeastConnection(BasicConnection): heartbeat_interval = 30.0 @staticmethod def describe(): return 'Beast-format results connection' def __init__(self, listener, socket, s_family, s_type, addr): super().__init__(listener, socket, s_family, s_type, addr) self.writebuf = bytearray() self.last_write = monotonic_time() def heartbeat(self, now): if (now - self.last_write) > 30.0: # write a keepalive frame self.send(b'\x1A1\x00\x00\x00\x00\x00\x00\x00\x00\x00') self.last_write = now def send_frame(self, frame): """Send a 14-byte message in the Beast binary format, using the magic mlat timestamp""" # format: # 1A '3' long frame follows # FF 00 'MLAT' 6-byte timestamp, this is the magic MLAT timestamp # 00 signal level # ... 14 bytes of frame data, with 1A bytes doubled self.writebuf.extend(b'\x1A3\xFF\x00MLAT\x00') if b'\x1a' not in frame: self.writebuf.extend(frame) else: for b in frame: if b == 0x1A: self.writebuf.append(b) self.writebuf.append(b) self.last_write = monotonic_time() def send_position(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate, callsign, squawk, error_est, nstations, anon, modeac): if not self.connected: return if modeac: df = DF18TRACK elif anon: df = DF18ANON else: df = DF18 if lat is None or lon is None: if alt is not None: self.send_frame(make_altitude_only_frame(addr, alt, df=df)) else: even, odd = make_position_frame_pair(addr, lat, lon, alt, df=df) self.send_frame(even) self.send_frame(odd) if nsvel is not None or ewvel is not None or vrate is not None: self.send_frame(make_velocity_frame(addr, nsvel, ewvel, vrate, df=df)) mlat-client-adsbfi/mlat/client/net.py0000644000175100017510000001472614702220435017331 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Common networking bits, based on asyncore """ import sys import socket import asyncore from mlat.client.util import log, log_exc, monotonic_time import random random.seed() __all__ = ('LoggingMixin', 'ReconnectingConnection') class LoggingMixin: """A mixin that redirects asyncore's logging to the client's global logging.""" def log(self, message): log('{0}', message) def log_info(self, message, type='info'): log('{0}: {1}', message, type) class ReconnectingConnection(LoggingMixin, asyncore.dispatcher): """ An asyncore connection that maintains a TCP connection to a particular host/port, reconnecting on connection loss. """ reconnect_interval = 10.0 def __init__(self, host, port): asyncore.dispatcher.__init__(self) self.host = host self.port = port # check port as well, if port doesn't match, could be direct MLAT if self.host == 'feed.adsb.fi' and port == 31090: self.adsbexchange = True else: self.adsbexchange = False self.adsbexchangePortIndex = 0 self.adsbexchangeHostIndex = 0 self.adsbexchangePorts = [ 31090, 64590 ] self.adsbexchangeHosts = [ 'feed1.adsb.fi', 'feed2.adsb.fi' ] self.addrlist = [] self.state = 'disconnected' self.reconnect_at = None self.last_try = 0 def heartbeat(self, now): if self.reconnect_at is None or self.reconnect_at > now: return if self.state == 'ready': return self.reconnect_at = None self.reconnect() def close(self, manual_close=False): try: asyncore.dispatcher.close(self) except AttributeError: # blarg, try to eat asyncore bugs pass if self.state != 'disconnected': if not manual_close: log('Lost connection to {host}:{port}', host=self.host, port=self.port) self.state = 'disconnected' self.reset_connection() self.lost_connection() if not manual_close: self.schedule_reconnect() def disconnect(self, reason): if self.state != 'disconnected': log('Disconnecting from {host}:{port}: {reason}', host=self.host, port=self.port, reason=reason) self.close(True) def writable(self): return self.connecting def schedule_reconnect(self): if self.reconnect_at is None: mono = monotonic_time() if len(self.addrlist) > 0: # we still have more addresses to try # nb: asyncore breaks in odd ways if you try # to reconnect immediately at this point # (pending events for the old socket go to # the new socket) so do it in 0.5s time # so the caller can clean up the old # socket and discard the events. interval = 0.5 else: interval = self.last_try + self.reconnect_interval - mono + 2 * random.random() if interval < 4: interval = 2 + 2 * random.random() log('Reconnecting in {seconds:.1f} seconds'.format(seconds=interval)) self.reconnect_at = mono + interval def refresh_address_list(self): self.address def reconnect(self): if self.state != 'disconnected': self.disconnect('About to reconnect') self.last_try = monotonic_time() try: self.reset_connection() if len(self.addrlist) == 0: # ran out of addresses to try, resolve it again if self.adsbexchange: self.adsbexchangePortIndex = (self.adsbexchangePortIndex + 1) % len(self.adsbexchangePorts) self.adsbexchangeHostIndex = (self.adsbexchangeHostIndex + 1) % len(self.adsbexchangeHosts) self.host = self.adsbexchangeHosts[self.adsbexchangeHostIndex]; self.port = self.adsbexchangePorts[self.adsbexchangePortIndex]; self.addrlist = socket.getaddrinfo(host=self.host, port=self.port, family=socket.AF_UNSPEC, type=socket.SOCK_STREAM, proto=0, flags=0) # try the next available address a_family, a_type, a_proto, a_canonname, a_sockaddr = self.addrlist[0] del self.addrlist[0] self.create_socket(a_family, a_type) self.connect(a_sockaddr) except socket.error as e: log('Connection to {host}:{port} failed: {ex!s}', host=self.host, port=self.port, ex=e) self.close() def handle_connect(self): self.state = 'connected' self.addrlist = [] # connect was OK, re-resolve next time self.start_connection() def handle_read(self): pass def handle_write(self): pass def handle_close(self): self.close() def handle_error(self): t, v, tb = sys.exc_info() if isinstance(v, IOError): log('Connection to {host}:{port} lost: {ex!s}', host=self.host, port=self.port, ex=v) else: log_exc('Unexpected exception on connection to {host}:{port}', host=self.host, port=self.port) self.handle_close() def reset_connection(self): pass def start_connection(self): pass def lost_connection(self): pass mlat-client-adsbfi/mlat/client/stats.py0000644000175100017510000000505714702220435017676 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Global stats gathering. """ from mlat.client.util import monotonic_time, log class Stats: def __init__(self): self.reset() def reset(self, now=None): if now is None: now = monotonic_time() self.start = now self.server_tx_bytes = 0 self.server_rx_bytes = 0 self.server_udp_bytes = 0 self.receiver_rx_bytes = 0 self.receiver_rx_messages = 0 self.receiver_rx_filtered = 0 self.receiver_rx_mlat = 0 self.mlat_positions = 0 def log_and_reset(self, coordinator): now = monotonic_time() elapsed = now - self.start #log('Receiver status: {0}', coordinator.receiver.state) #log('Server status: {0}', coordinator.server.state) coordinator.print_server_statistics = True processed = self.receiver_rx_messages - self.receiver_rx_filtered log('Receiver: {3:10s} {0:6.1f} msg/s received {1:6.1f} msg/s processed ({2:.0f}%)', self.receiver_rx_messages / elapsed, processed / elapsed, 0 if self.receiver_rx_messages == 0 else 100.0 * processed / self.receiver_rx_messages, coordinator.receiver.state) if self.receiver_rx_mlat: log('WARNING: Ignored {0:5d} messages with MLAT magic timestamp (do you have --forward-mlat on?)', self.receiver_rx_mlat) log('Server: {0:10s} {1:6.1f} kB/s from server {2:6.1f} kB/s to server', coordinator.server.state, self.server_rx_bytes / elapsed / 1000.0, (self.server_tx_bytes + self.server_udp_bytes) / elapsed / 1000.0) log('Results: {0:3.1f} positions/minute', self.mlat_positions / elapsed * 60.0) self.reset(now) global_stats = Stats() mlat-client-adsbfi/mlat/client/receiver.py0000644000175100017510000002414014702220435020336 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Handles receiving Mode S messages from receivers using various formats. """ import socket import errno import _modes import mlat.profile from mlat.client.stats import global_stats from mlat.client.net import ReconnectingConnection from mlat.client.util import log, monotonic_time class ReceiverConnection(ReconnectingConnection): inactivity_timeout = 150.0 def __init__(self, host, port, mode): ReconnectingConnection.__init__(self, host, port) self.coordinator = None self.last_data_received = monotonic_time() self.mode = mode # set up filters # this set gets put into specific_filter in # multiple places, so we can just add an address # to this set when we want mlat data. self.interested_mlat = set() self.default_filter = [False] * 32 self.specific_filter = [None] * 32 # specific filters for mlat for df in (0, 4, 5, 11, 16, 20, 21): self.specific_filter[df] = self.interested_mlat # we want all DF17 messages so we can report position rates # and distinguish ADS-B from Mode-S-only aircraft self.default_filter[17] = True self.modeac_filter = set() self.reset_connection() def detect(self, data): n, detected_mode = detect_data_format(data) if detected_mode is not None: log("Detected {mode} format input".format(mode=detected_mode)) if detected_mode == _modes.AVR: log("Input format is AVR with no timestamps. " "This format does not contain enough information for multilateration. " "Please enable mlat timestamps on your receiver.") self.close() return (0, (), False) self.reader.mode = detected_mode self.feed = self.reader.feed # synthesize a mode-change event before the real messages mode_change = (mode_change_event(self.reader), ) try: m, messages, pending_error = self.feed(data[n:]) except ValueError: # return just the mode change and keep the error pending return (n, mode_change, True) # put the mode change on the front of the message list return (n + m, mode_change + messages, pending_error) else: if len(data) > 512: raise ValueError('Unable to autodetect input message format') return (0, (), False) def reset_connection(self): self.residual = None self.reader = _modes.Reader(self.mode) if self.mode is None: self.feed = self.detect else: self.feed = self.reader.feed # configure filter, seen-tracking self.reader.seen = set() self.reader.default_filter = self.default_filter self.reader.specific_filter = self.specific_filter self.reader.modeac_filter = self.modeac_filter def start_connection(self): log('Input connected to {0}:{1}', self.host, self.port) self.last_data_received = monotonic_time() self.state = 'connected' self.coordinator.input_connected() # synthesize a mode change immediately if we are not autodetecting if self.reader.mode is not None: self.coordinator.input_received_messages((mode_change_event(self.reader),)) self.send_settings_message() def send_settings_message(self): # if we are connected to something that is Beast-like (or autodetecting), send a beast settings message if self.state != 'connected': return if self.reader.mode not in (None, _modes.BEAST, _modes.RADARCAPE, _modes.RADARCAPE_EMULATED): return if not self.modeac_filter: # Binary format, no filters, CRC checks enabled, mode A/C disabled settings_message = b'\x1a1C\x1a1d\x1a1f\x1a1j' else: # Binary format, no filters, CRC checks enabled, mode A/C enabled settings_message = b'\x1a1C\x1a1d\x1a1f\x1a1J' self.send(settings_message) def lost_connection(self): self.coordinator.input_disconnected() def heartbeat(self, now): ReconnectingConnection.heartbeat(self, now) if self.state == 'connected' and (now - self.last_data_received) > self.inactivity_timeout: self.disconnect('No data (not even keepalives) received for {0:.0f} seconds'.format( self.inactivity_timeout)) self.reconnect() def recent_aircraft(self): """Return the set of aircraft seen from the receiver since the last call to recent_aircraft(). This includes aircraft where no messages were forwarded due to filtering.""" recent = set(self.reader.seen) self.reader.seen.clear() return recent def update_filter(self, wanted_mlat): """Update the receiver filters so we receive mlat-relevant messages (basically, anything that's not DF17) for the given addresses only.""" # do this in place, because self.interested_mlat is referenced # from the filters installed on the reader; updating the set in # place automatically updates all the DF-specific filters. self.interested_mlat.clear() self.interested_mlat.update(wanted_mlat) def update_modeac_filter(self, wanted_modeac): """Update the receiver filters so that we receive mode A/C messages for the given Mode A codes""" changed = (self.modeac_filter and not wanted_modeac) or (not self.modeac_filter and wanted_modeac) self.modeac_filter.clear() self.modeac_filter.update(wanted_modeac) if changed: self.send_settings_message() @mlat.profile.trackcpu def handle_read(self): try: moredata = self.recv(16384) except socket.error as e: if e.errno == errno.EAGAIN: return raise if not moredata: self.close() return global_stats.receiver_rx_bytes += len(moredata) if self.residual: moredata = self.residual + moredata self.last_data_received = monotonic_time() try: consumed, messages, pending_error = self.feed(moredata) except ValueError as e: log("Parsing receiver data failed: {e}", e=str(e)) self.close() return if consumed < len(moredata): self.residual = moredata[consumed:] if len(self.residual) > 5120: raise RuntimeError('parser broken - buffer not being consumed') else: self.residual = None global_stats.receiver_rx_messages += self.reader.received_messages global_stats.receiver_rx_filtered += self.reader.suppressed_messages global_stats.receiver_rx_mlat += self.reader.mlat_messages self.reader.received_messages = self.reader.suppressed_messages = self.reader.mlat_messages = 0 if messages: self.coordinator.input_received_messages(messages) if pending_error: # call it again to get the exception # now that we've handled all the messages try: if self.residual is None: self.feed(b'') else: self.feed(self.residual) except ValueError as e: log("Parsing receiver data failed: {e}", e=str(e)) self.close() return def mode_change_event(reader): return _modes.EventMessage(_modes.DF_EVENT_MODE_CHANGE, 0, { "mode": reader.mode, "frequency": reader.frequency, "epoch": reader.epoch}) def detect_data_format(data): """Try to work out what sort of data format this is. Returns (offset, mode) where offset is the byte offset to start at and mode is the decoder mode to use, or None if detection failed.""" for i in range(len(data)-4): mode = None if data[i] != b'\x1a' and data[i+1:i+3] in (b'\x1a1', b'\x1a2', b'\x1a3', b'\x1a4'): mode = _modes.BEAST offset = 1 elif data[i:i+4] == b'\x10\0x03\x10\0x02': mode = _modes.SBS offset = 2 else: if data[i:i+3] in (b';\n\r', b';\r\n'): avr_prefix = 3 elif data[i:i+2] in (b';\n', b';\r'): avr_prefix = 2 else: avr_prefix = None if avr_prefix: firstbyte = data[i + avr_prefix] if firstbyte in (ord('@'), ord('%'), ord('<')): mode = _modes.AVRMLAT offset = avr_prefix elif firstbyte in (ord('*'), ord('.')): mode = _modes.AVR offset = avr_prefix if mode: reader = _modes.Reader(mode) # don't actually want any data, just parse it reader.want_events = False reader.default_filter = [False] * 32 try: n, _, pending_error = reader.feed(data[i + offset:]) if n > 0 and not pending_error: # consumed some data without problems return (i + offset, mode) except ValueError: # parse error, ignore it pass return (0, None) mlat-client-adsbfi/mlat/client/synthetic_es.py0000644000175100017510000002246014702220435021236 0ustar debiandebian# -*- python -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import math import _modes import bisect # It would be nice to merge this into a proper all-singing # all-dancing Mode S module that combined _modes, this code, # and the server side Mode S decoder. A task for another day.. __all__ = ('make_altitude_only_frame', 'make_position_frame_pair', 'make_velocity_frame', 'DF17', 'DF18') # types of frame we can build DF17 = 'DF17' DF18 = 'DF18' DF18ANON = 'DF18ANON' DF18TRACK = 'DF18TRACK' # lookup table for CPR_NL nl_table = ( (10.47047130, 59), (14.82817437, 58), (18.18626357, 57), (21.02939493, 56), (23.54504487, 55), (25.82924707, 54), (27.93898710, 53), (29.91135686, 52), (31.77209708, 51), (33.53993436, 50), (35.22899598, 49), (36.85025108, 48), (38.41241892, 47), (39.92256684, 46), (41.38651832, 45), (42.80914012, 44), (44.19454951, 43), (45.54626723, 42), (46.86733252, 41), (48.16039128, 40), (49.42776439, 39), (50.67150166, 38), (51.89342469, 37), (53.09516153, 36), (54.27817472, 35), (55.44378444, 34), (56.59318756, 33), (57.72747354, 32), (58.84763776, 31), (59.95459277, 30), (61.04917774, 29), (62.13216659, 28), (63.20427479, 27), (64.26616523, 26), (65.31845310, 25), (66.36171008, 24), (67.39646774, 23), (68.42322022, 22), (69.44242631, 21), (70.45451075, 20), (71.45986473, 19), (72.45884545, 18), (73.45177442, 17), (74.43893416, 16), (75.42056257, 15), (76.39684391, 14), (77.36789461, 13), (78.33374083, 12), (79.29428225, 11), (80.24923213, 10), (81.19801349, 9), (82.13956981, 8), (83.07199445, 7), (83.99173563, 6), (84.89166191, 5), (85.75541621, 4), (86.53536998, 3), (87.00000000, 2), (90.00000000, 1) ) nl_lats = [x[0] for x in nl_table] nl_vals = [x[1] for x in nl_table] def CPR_NL(lat): """The NL function referenced in the CPR calculations: the number of longitude zones at a given latitude""" if lat < 0: lat = -lat nl = nl_vals[bisect.bisect_left(nl_lats, lat)] return nl def CPR_N(lat, odd): """The N function referenced in the CPR calculations: the number of longitude zones at a given latitude / oddness""" nl = CPR_NL(lat) - (odd and 1 or 0) if nl < 1: nl = 1 return nl def cpr_encode(lat, lon, odd): """Encode an airborne position using a CPR encoding with the given odd flag value""" NbPow = 2**17 Dlat = 360.0 / (odd and 59 or 60) YZ = int(math.floor(NbPow * (lat % Dlat) / Dlat + 0.5)) Rlat = Dlat * (1.0 * YZ / NbPow + math.floor(lat / Dlat)) Dlon = (360.0 / CPR_N(Rlat, odd)) XZ = int(math.floor(NbPow * (lon % Dlon) / Dlon + 0.5)) return (YZ & 0x1FFFF), (XZ & 0x1FFFF) def encode_altitude(ft): """Encode an altitude in feet using the representation expected in DF17 messages""" if ft is None: return 0 i = int((ft + 1012.5) / 25) if i < 0: i = 0 elif i > 0x7ff: i = 0x7ff # insert Q=1 in bit 4 return ((i & 0x7F0) << 1) | 0x010 | (i & 0x00F) def encode_velocity(kts, supersonic): """Encode a groundspeed in kts using the representation expected in DF17 messages""" if kts is None: return 0 if kts < 0: signbit = 0x400 kts = 0 - kts else: signbit = 0 if supersonic: kts /= 4 kts = int(kts + 1.5) if kts > 1023: return 1023 | signbit else: return kts | signbit def encode_vrate(vr): """Encode a vertical rate in fpm using the representation expected in DF17 messages""" if vr is None: return 0 if vr < 0: signbit = 0x200 vr = 0 - vr else: signbit = 0 vr = int(vr / 64 + 1.5) if vr > 511: return 511 | signbit else: return vr | signbit def make_altitude_only_frame(addr, lat, lon, alt, df=DF18): """Create an altitude-only DF17 frame""" # ME type 0: airborne position, horizontal position unavailable return make_position_frame(0, addr, 0, 0, encode_altitude(alt), False, df) def make_position_frame_pair(addr, lat, lon, alt, df=DF18): """Create a pair of DF17 frames - one odd, one even - for the given position""" ealt = encode_altitude(alt) even_lat, even_lon = cpr_encode(lat, lon, False) odd_lat, odd_lon = cpr_encode(lat, lon, True) # ME type 18: airborne position, baro alt, NUCp=0 eframe = make_position_frame(18, addr, even_lat, even_lon, ealt, False, df) oframe = make_position_frame(18, addr, odd_lat, odd_lon, ealt, True, df) return eframe, oframe def make_position_frame(metype, addr, elat, elon, ealt, oddflag, df): """Create single DF17/DF18 position frame""" frame = bytearray(14) if df is DF17: # DF=17, CA=6 (ES, Level 2 or above transponder and ability # to set CA code 7 and either airborne or on the ground) frame[0] = (17 << 3) | (6) imf = 0 elif df is DF18: # DF=18, CF=2, IMF=0 (ES/NT, fine TIS-B message with 24-bit address) frame[0] = (18 << 3) | (2) imf = 0 elif df is DF18ANON: # DF=18, CF=5, IMF=0 (ES/NT, fine TIS-B message with anonymous 24-bit address) frame[0] = (18 << 3) | (5) imf = 0 elif df is DF18TRACK: # DF=18, CF=2, IMF=1 (ES/NT, fine TIS-B message with track file number) frame[0] = (18 << 3) | (2) imf = 1 else: raise ValueError('df must be DF17 or DF18 or DF18ANON or DF18TRACK') frame[1] = (addr >> 16) & 255 # AA frame[2] = (addr >> 8) & 255 # AA frame[3] = addr & 255 # AA frame[4] = (metype << 3) # ME type, status 0 frame[4] |= imf # SAF (DF17) / IMF (DF 18) frame[5] = (ealt >> 4) & 255 # Altitude (MSB) frame[6] = (ealt & 15) << 4 # Altitude (LSB) if oddflag: frame[6] |= 4 # CPR format frame[6] |= (elat >> 15) & 3 # CPR latitude (top bits) frame[7] = (elat >> 7) & 255 # CPR latitude (middle bits) frame[8] = (elat & 127) << 1 # CPR latitude (low bits) frame[8] |= (elon >> 16) & 1 # CPR longitude (high bit) frame[9] = (elon >> 8) & 255 # CPR longitude (middle bits) frame[10] = elon & 255 # CPR longitude (low bits) # CRC c = _modes.crc(frame[0:11]) frame[11] = (c >> 16) & 255 frame[12] = (c >> 8) & 255 frame[13] = c & 255 return frame def make_velocity_frame(addr, nsvel, ewvel, vrate, df=DF18): """Create a DF17/DF18 airborne velocity frame""" supersonic = (nsvel is not None and abs(nsvel) > 1000) or (ewvel is not None and abs(ewvel) > 1000) e_ns = encode_velocity(nsvel, supersonic) e_ew = encode_velocity(ewvel, supersonic) e_vr = encode_vrate(vrate) frame = bytearray(14) if df is DF17: # DF=17, CA=6 (ES, Level 2 or above transponder and ability # to set CA code 7 and either airborne or on the ground) frame[0] = (17 << 3) | (6) imf = 0 elif df is DF18: # DF=18, CF=2, IMF=0 (ES/NT, fine TIS-B message with 24-bit address) frame[0] = (18 << 3) | (2) imf = 0 elif df is DF18ANON: # DF=18, CF=5, IMF=1 (ES/NT, fine TIS-B message with anonymous 24-bit address) frame[0] = (18 << 3) | (5) imf = 0 elif df is DF18TRACK: # DF=18, CF=2, IMF=1 (ES/NT, fine TIS-B message with track file number) frame[0] = (18 << 3) | (2) imf = 1 else: raise ValueError('df must be DF17 or DF18 or DF18ANON or DF18TRACK') frame[1] = (addr >> 16) & 255 # AA frame[2] = (addr >> 8) & 255 # AA frame[3] = addr & 255 # AA frame[4] = (19 << 3) # ES type 19, airborne velocity if supersonic: frame[4] |= 2 # subtype 2, ground speed, supersonic else: frame[4] |= 1 # subtype 1, ground speed, subsonic frame[5] = (imf << 7) # IMF, NACp 0 frame[5] |= (e_ew >> 8) & 7 # E/W velocity sign and top bits frame[6] = (e_ew & 255) # E/W velocity low bits frame[7] = (e_ns >> 3) & 255 # N/S velocity top bits frame[8] = (e_ns & 7) << 5 # N/S velocity low bits frame[8] |= 16 # vertical rate source = baro frame[8] |= (e_vr >> 6) & 15 # vertical rate top bits frame[9] = (e_vr & 63) << 2 # vertical rate low bits frame[10] = 0 # GNSS/Baro alt offset, no data # CRC c = _modes.crc(frame[0:11]) frame[11] = (c >> 16) & 255 frame[12] = (c >> 8) & 255 frame[13] = c & 255 return frame mlat-client-adsbfi/mlat/client/__init__.py0000644000175100017510000000000014702220435020256 0ustar debiandebianmlat-client-adsbfi/mlat/client/util.py0000644000175100017510000000356714702220435017521 0ustar debiandebian# -*- python -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import sys import time import traceback __all__ = ('log', 'log_exc', 'monotonic_time') suppress_log_timestamps = True def log(msg, *args, **kwargs): if suppress_log_timestamps: print(msg.format(*args, **kwargs), file=sys.stderr) else: print(time.ctime(), msg.format(*args, **kwargs), file=sys.stderr) sys.stderr.flush() def log_exc(msg, *args, **kwargs): if suppress_log_timestamps: print(msg.format(*args, **kwargs), file=sys.stderr) else: print(time.ctime(), msg.format(*args, **kwargs), file=sys.stderr) traceback.print_exc(file=sys.stderr) sys.stderr.flush() _adjust = 0 _last = 0 def monotonic_time(): """Emulates time.monotonic() if not available.""" global _adjust, _last now = time.time() if now < _last: # system clock went backwards, add in a # fudge factor so our monotonic clock # does not. _adjust = _adjust + (_last - now) _last = now return now + _adjust try: # try to use the 3.3+ version when available from time import monotonic as monotonic_time # noqa except ImportError: pass mlat-client-adsbfi/mlat/client/jsonclient.py0000644000175100017510000004747714702220435020724 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ The JSON client/server protocol, client side. """ import math import time import struct import zlib import socket import errno import json import mlat.client.version import mlat.client.net import mlat.profile import mlat.geodesy from mlat.client.util import log, monotonic_time from mlat.client.stats import global_stats DEBUG = False # UDP protocol submessages TYPE_SYNC = 1 TYPE_MLAT_SHORT = 2 TYPE_MLAT_LONG = 3 TYPE_SSYNC = 4 TYPE_REBASE = 5 TYPE_ABS_SYNC = 6 STRUCT_HEADER = struct.Struct(">IHQ") STRUCT_SYNC = struct.Struct(">Bii14s14s") STRUCT_SSYNC = struct.Struct(">Bi14s") STRUCT_MLAT_SHORT = struct.Struct(">Bi7s") STRUCT_MLAT_LONG = struct.Struct(">Bi14s") STRUCT_REBASE = struct.Struct(">BQ") STRUCT_ABS_SYNC = struct.Struct(">BQQ14s14s") class UdpServerConnection: def __init__(self, host, port, key): self.host = host self.port = port self.key = key self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.sock.connect((host, port)) self.base_timestamp = None self.header_timestamp = None self.buf = bytearray(1500) self.used = 0 self.seq = 0 def prepare_header(self, timestamp): self.base_timestamp = timestamp STRUCT_HEADER.pack_into(self.buf, 0, self.key, self.seq, self.base_timestamp) self.used += STRUCT_HEADER.size def rebase(self, timestamp): self.base_timestamp = timestamp STRUCT_REBASE.pack_into(self.buf, self.used, TYPE_REBASE, self.base_timestamp) self.used += STRUCT_REBASE.size def send_mlat(self, message): if not self.used: self.prepare_header(message.timestamp) delta = message.timestamp - self.base_timestamp if abs(delta) > 0x7FFFFFF0: self.rebase(message.timestamp) delta = 0 if len(message) == 7: STRUCT_MLAT_SHORT.pack_into(self.buf, self.used, TYPE_MLAT_SHORT, delta, bytes(message)) self.used += STRUCT_MLAT_SHORT.size else: STRUCT_MLAT_LONG.pack_into(self.buf, self.used, TYPE_MLAT_LONG, delta, bytes(message)) self.used += STRUCT_MLAT_LONG.size if self.used > 1400: self.flush() def send_sync(self, em, om): if not self.used: self.prepare_header(int((em.timestamp + om.timestamp) / 2)) if abs(em.timestamp - om.timestamp) > 0xFFFFFFF0: # use abs sync STRUCT_ABS_SYNC.pack_into(self.buf, self.used, TYPE_ABS_SYNC, em.timestamp, om.timestamp, bytes(em), bytes(om)) self.used += STRUCT_ABS_SYNC.size else: edelta = em.timestamp - self.base_timestamp odelta = om.timestamp - self.base_timestamp if abs(edelta) > 0x7FFFFFF0 or abs(odelta) > 0x7FFFFFF0: self.rebase(int((em.timestamp + om.timestamp) / 2)) edelta = em.timestamp - self.base_timestamp odelta = om.timestamp - self.base_timestamp STRUCT_SYNC.pack_into(self.buf, self.used, TYPE_SYNC, edelta, odelta, bytes(em), bytes(om)) self.used += STRUCT_SYNC.size if self.used > 1400: self.flush() def send_split_sync(self, m): if not self.used: self.prepare_header(m.timestamp) delta = m.timestamp - self.base_timestamp if abs(delta) > 0x7FFFFFF0: self.rebase(m.timestamp) delta = 0 STRUCT_SSYNC.pack_into(self.buf, self.used, TYPE_SSYNC, delta, bytes(m)) self.used += STRUCT_SSYNC.size if self.used > 1400: self.flush() def flush(self): if not self.used: return try: self.sock.send(memoryview(self.buf)[0:self.used]) except socket.error: pass global_stats.server_udp_bytes += self.used self.used = 0 self.base_timestamp = None self.seq = (self.seq + 1) & 0xffff def close(self): self.used = 0 self.sock.close() def __str__(self): return '{0}:{1}'.format(self.host, self.port) class JsonServerConnection(mlat.client.net.ReconnectingConnection): reconnect_interval = 10.0 heartbeat_interval = 120.0 inactivity_timeout = 60.0 def __init__(self, host, port, uuid_path, uuid, handshake_data, offer_zlib, offer_udp, return_results): super().__init__(host, port) self.uuid_path = uuid_path self.handshake_data = handshake_data self.offer_zlib = offer_zlib self.offer_udp = offer_udp self.return_results = return_results self.coordinator = None self.udp_transport = None self.last_clock_reset = time.monotonic() self.uuid = None if uuid is not None: self.uuid = uuid else: for path in self.uuid_path: try: with open(path) as file: self.uuid = file.readline().rstrip('\n') break except Exception: pass self.reset_connection() def start(self): self.reconnect() def reset_connection(self): self.readbuf = bytearray() self.writebuf = bytearray() self.linebuf = [] self.fill_writebuf = None self.handle_server_line = None self.server_heartbeat_at = None self.last_data_received = None if self.udp_transport: self.udp_transport.close() self.udp_transport = None def lost_connection(self): self.coordinator.server_disconnected() def readable(self): return self.handle_server_line is not None def writable(self): return self.connecting or self.writebuf or (self.fill_writebuf and self.linebuf and self.coordinator.server_send) @mlat.profile.trackcpu def handle_write(self): self.coordinator.server_send = 0 if self.fill_writebuf: self.fill_writebuf() if self.writebuf: sent = self.send(self.writebuf) del self.writebuf[:sent] global_stats.server_tx_bytes += sent if len(self.writebuf) > 65536: raise IOError('Server write buffer overflow (too much unsent data)') def fill_uncompressed(self): if not self.linebuf: return lines = '\n'.join(self.linebuf) self.writebuf.extend(lines.encode('ascii')) self.writebuf.extend(b'\n') self.linebuf = [] def fill_zlib(self): if not self.linebuf: return data = bytearray() pending = False for line in self.linebuf: data.extend(self.compressor.compress((line + '\n').encode('ascii'))) pending = True if len(data) >= 32768: data.extend(self.compressor.flush(zlib.Z_SYNC_FLUSH)) assert len(data) < 65540 assert data[-4:] == b'\x00\x00\xff\xff' del data[-4:] self.writebuf.extend(struct.pack('!H', len(data))) self.writebuf.extend(data) pending = False if pending: data.extend(self.compressor.flush(zlib.Z_SYNC_FLUSH)) assert len(data) < 65540 assert data[-4:] == b'\x00\x00\xff\xff' del data[-4:] self.writebuf.extend(struct.pack('!H', len(data))) self.writebuf.extend(data) self.linebuf = [] def _send_json(self, o): if DEBUG: log('Send: {0}', o) self.linebuf.append(json.dumps(o, separators=(',', ':'))) # # TCP transport # def send_tcp_mlat(self, message): self.linebuf.append('{{"mlat":{{"t":{0},"m":"{1}"}}}}'.format( message.timestamp, str(message))) def send_tcp_sync(self, em, om): self.linebuf.append('{{"sync":{{"et":{0},"em":"{1}","ot":{2},"om":"{3}"}}}}'.format( em.timestamp, str(em), om.timestamp, str(om))) def send_tcp_split_sync(self, m): self.linebuf.append('{{"ssync":{{"t":{0},"m":"{1}"}}}}'.format( m.timestamp, str(m))) def send_seen(self, aclist): self._send_json({'seen': ['{0:06x}'.format(icao) for icao in aclist]}) def send_lost(self, aclist): self._send_json({'lost': ['{0:06x}'.format(icao) for icao in aclist]}) def send_rate_report(self, report): r2 = dict([('{0:06X}'.format(k), round(v, 2)) for k, v in report.items()]) self._send_json({'rate_report': r2}) def send_input_connected(self): self._send_json({'input_connected': 'connected'}) def send_input_disconnected(self): self._send_json({'input_disconnected': 'disconnected'}) def send_clock_jump(self): now = time.monotonic() if now > self.last_clock_reset + 0.5: self.last_clock_reset = now self._send_json({'clock_jump': True}) def send_clock_reset(self, reason, frequency=None, epoch=None, mode=None): details = { 'reason': reason } if frequency is not None: details['frequency'] = frequency details['epoch'] = epoch details['mode'] = mode self._send_json({'clock_reset': details}) def send_position_update(self, lat, lon, alt, altref): pass def start_connection(self): log('Connected to multilateration server at {0}:{1}, handshaking', self.host, self.port) self.state = 'handshaking' self.last_data_received = monotonic_time() compress_methods = ['none'] if self.offer_zlib: compress_methods.append('zlib') compress_methods.append('zlib2') handshake_msg = {'version': 3, 'client_version': mlat.client.version.CLIENT_VERSION, 'compress': compress_methods, 'selective_traffic': True, 'heartbeat': True, 'return_results': self.return_results, 'udp_transport': 2 if self.offer_udp else False, 'return_result_format': 'ecef', 'return_stats': True, 'uuid': self.uuid} handshake_msg.update(self.handshake_data) if DEBUG: log("Handshake: {0}", handshake_msg) self.writebuf += (json.dumps(handshake_msg, sort_keys=True) + 16 * ' ' + '\n').encode('ascii') # linebuf not used yet self.consume_readbuf = self.consume_readbuf_uncompressed self.handle_server_line = self.handle_handshake_response def heartbeat(self, now): super().heartbeat(now) if self.state in ('ready', 'handshaking') and (now - self.last_data_received) > self.inactivity_timeout: self.disconnect('No data (not even keepalives) received for {0:.0f} seconds'.format( self.inactivity_timeout)) self.reconnect() return if self.udp_transport: self.udp_transport.flush() if self.server_heartbeat_at is not None and self.server_heartbeat_at < now: self.server_heartbeat_at = now + self.heartbeat_interval self._send_json({'heartbeat': {'client_time': round(time.time(), 3)}}) def handle_read(self): try: moredata = self.recv(16384) except socket.error as e: if e.errno == errno.EAGAIN: return raise if not moredata: log("handle_read: moredata is falsy, reconnecting") self.close() self.schedule_reconnect() return self.last_data_received = monotonic_time() self.readbuf += moredata global_stats.server_rx_bytes += len(moredata) self.consume_readbuf() def consume_readbuf_uncompressed(self): lines = self.readbuf.split(b'\n') self.readbuf = lines[-1] for line in lines[:-1]: try: msg = json.loads(line.decode('ascii')) except ValueError: log("json parsing problem, line: >>{line}<<", line=line) raise if DEBUG: log('Receive: {0}', msg) self.handle_server_line(msg) def consume_readbuf_zlib(self): i = 0 while i + 2 < len(self.readbuf): hlen, = struct.unpack_from('!H', self.readbuf, i) end = i + 2 + hlen if end > len(self.readbuf): break packet = self.readbuf[i + 2:end] + b'\x00\x00\xff\xff' linebuf = self.decompressor.decompress(packet) lines = linebuf.split(b'\n') for line in lines[:-1]: try: msg = json.loads(line.decode('ascii')) except ValueError: log("json parsing problem, line: >>{line}<<", line=line) raise self.handle_server_line(msg) i = end del self.readbuf[:i] def handle_handshake_response(self, response): if 'reconnect_in' in response: self.reconnect_interval = response['reconnect_in'] if 'deny' in response: log('Server explicitly rejected our connection, saying:') for reason in response['deny']: log(' {0}', reason) raise IOError('Server rejected our connection attempt') if 'motd' in response: log('Server says: {0}', response['motd']) compress = response.get('compress', 'none') if response['compress'] == 'none': self.fill_writebuf = self.fill_uncompressed self.consume_readbuf = self.consume_readbuf_uncompressed elif response['compress'] == 'zlib' and self.offer_zlib: self.compressor = zlib.compressobj(1) self.fill_writebuf = self.fill_zlib self.consume_readbuf = self.consume_readbuf_uncompressed elif response['compress'] == 'zlib2' and self.offer_zlib: self.compressor = zlib.compressobj(1) self.decompressor = zlib.decompressobj() self.fill_writebuf = self.fill_zlib self.consume_readbuf = self.consume_readbuf_zlib else: raise IOError('Server response asked for a compression method {0}, which we do not support'.format( response['compress'])) self.server_heartbeat_at = monotonic_time() + self.heartbeat_interval if 'udp_transport' in response: host, port, key = response['udp_transport'] if not host: host = self.host self.udp_transport = UdpServerConnection(host, port, key) self.send_mlat = self.udp_transport.send_mlat self.send_sync = self.udp_transport.send_sync self.send_split_sync = self.udp_transport.send_split_sync else: self.udp_transport = None self.send_mlat = self.send_tcp_mlat self.send_sync = self.send_tcp_sync self.send_split_sync = self.send_tcp_split_sync # turn off the sync method we don't want if response.get('split_sync', False): self.send_sync = None else: self.send_split_sync = None log('Handshake complete: Compression {0}, UDP transport {1}, Split sync {2}', compress, self.udp_transport and str(self.udp_transport) or 'disabled', self.send_split_sync and 'enabled' or 'disabled') self.state = 'ready' self.handle_server_line = self.handle_connected_request self.coordinator.server_connected() # dummy rate report to indicate we'll be sending them self.send_rate_report({}) def handle_connected_request(self, request): if DEBUG: log('Receive: {0}', request) if 'start_sending' in request: self.coordinator.server_start_sending([int(x, 16) for x in request['start_sending']]) elif 'stop_sending' in request: self.coordinator.server_stop_sending([int(x, 16) for x in request['stop_sending']]) elif 'heartbeat' in request: pass elif 'result' in request: result = request['result'] ecef = result.get('ecef') if ecef is not None: # new format lat, lon, alt = mlat.geodesy.ecef2llh(ecef) alt = alt / 0.3038 # convert meters to feet ecef_cov = result.get('cov') if ecef_cov: var_est = ecef_cov[0] + ecef_cov[3] + ecef_cov[5] if var_est >= 0: error_est = math.sqrt(var_est) else: error_est = -1 else: error_est = -1 nstations = result['nd'] callsign = None squawk = None else: lat = result['lat'] lon = result['lon'] alt = result['alt'] error_est = result['gdop'] * 300 # make a guess nstations = result['nstations'] callsign = result['callsign'] squawk = result['squawk'] nsvel = result.get('nsvel') ewvel = result.get('ewvel') vrate = result.get('vrate') self.coordinator.server_mlat_result(timestamp=result['@'], addr=int(result['addr'], 16), lat=lat, lon=lon, alt=alt, nsvel=nsvel, ewvel=ewvel, vrate=vrate, callsign=callsign, squawk=squawk, error_est=error_est, nstations=nstations, anon=False, modeac=False) elif 'stats' in request: stats = request['stats'] if stats.get('bad_sync_timeout', 0) > 0 or self.coordinator.print_server_statistics: log('peer_count: {0:3.0f} outlier_percent: {1:2.1f} bad_sync_timeout: {2:3.0f}', stats.get("peer_count"), stats.get("outlier_percent"), stats.get("bad_sync_timeout")) self.coordinator.print_server_statistics = False else: log('ignoring request from server: {0}', request) mlat-client-adsbfi/mlat/client/version.py0000644000175100017510000000153014702220435020215 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """Just a version constant!""" CLIENT_VERSION = "0.4.2" mlat-client-adsbfi/mlat/client/coordinator.py0000644000175100017510000004056314702220435021064 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . """ Core of the client: track aircraft and send data to the server as needed. """ import asyncore import time import _modes import mlat.profile from mlat.client.util import monotonic_time, log from mlat.client.stats import global_stats import random random.seed() class Aircraft: """One tracked aircraft.""" def __init__(self, icao): self.icao = icao self.messages = 0 self.last_message_time = 0 self.last_even_time = 0 self.last_odd_time = 0 self.adsb_good = False self.even_message = None self.odd_message = None self.reported = False self.requested = True self.measurement_start = None self.rate_measurement_start = 0 self.recent_adsb_positions = 0 class Coordinator: update_interval = 4.5 report_interval = 4.0 # in multiples update_interval stats_interval = 900.0 position_expiry_age = 30.0 expiry_age = 120.0 def __init__(self, receiver, server, outputs, freq, allow_anon, allow_modeac): self.receiver = receiver self.server = server self.outputs = outputs self.freq = freq self.allow_anon = allow_anon self.allow_modeac = allow_modeac self.aircraft = {} self.requested_traffic = set() self.requested_modeac = set() self.reported = set() self.df_handlers = { _modes.DF_EVENT_MODE_CHANGE: self.received_mode_change_event, _modes.DF_EVENT_EPOCH_ROLLOVER: self.received_epoch_rollover_event, _modes.DF_EVENT_TIMESTAMP_JUMP: self.received_timestamp_jump_event, _modes.DF_EVENT_RADARCAPE_POSITION: self.received_radarcape_position_event, 0: self.received_df_misc, 4: self.received_df_misc, 5: self.received_df_misc, 16: self.received_df_misc, 20: self.received_df_misc, 21: self.received_df_misc, 11: self.received_df11, 17: self.received_df17, _modes.DF_MODEAC: self.received_modeac } self.next_report = None self.next_stats = monotonic_time() + 60 self.next_profile = monotonic_time() self.next_aircraft_update = self.last_aircraft_update = monotonic_time() self.recent_jumps = 0 self.last_jump_message = 0 self.server_send = 1 receiver.coordinator = self server.coordinator = self self.print_server_statistics = False # internals def run_forever(self): self.run_until(lambda: False) def run_until(self, termination_condition): try: next_heartbeat = monotonic_time() + 0.5 next_server_send = monotonic_time() while not termination_condition(): # maybe there are no active sockets and # we're just waiting on a timeout if asyncore.socket_map: asyncore.loop(timeout=0.1, count=5) else: time.sleep(0.5) now = monotonic_time() if now >= next_heartbeat: next_heartbeat = now + 0.5 self.heartbeat(now) if now >= next_server_send: self.server_send = 1 next_server_send = now + 0.25 finally: self.receiver.disconnect('Client shutting down') self.server.disconnect('Client shutting down') for o in self.outputs: o.disconnect('Client shutting down') def heartbeat(self, now): self.receiver.heartbeat(now) self.server.heartbeat(now) for o in self.outputs: o.heartbeat(now) if now >= self.next_profile: self.next_profile = now + 30.0 mlat.profile.dump_cpu_profiles() if now >= self.next_aircraft_update: self.next_aircraft_update = now + self.update_interval + random.random() self.update_aircraft(now) # piggyback reporting on regular updates # as the reporting uses data produced by the update if self.next_report is not None: self.next_report += 1.0 if self.next_report >= self.report_interval: #global_stats.log_and_reset(self) self.next_report = 0.0 self.send_aircraft_report() self.send_rate_report(now) if now >= self.next_stats: self.next_stats = now + self.stats_interval self.periodic_stats(now) def update_aircraft(self, now): # process aircraft the receiver has seen # (we have not necessarily seen any messages, # due to the receiver filter) for icao in self.receiver.recent_aircraft(): ac = self.aircraft.get(icao) if not ac: ac = Aircraft(icao) ac.requested = (icao in self.requested_traffic) ac.rate_measurement_start = now self.aircraft[icao] = ac if ac.last_message_time <= self.last_aircraft_update: # fudge it a bit, receiver has seen messages # but they were all filtered ac.messages += 1 ac.last_message_time = now if now - ac.last_even_time < self.position_expiry_age and now - ac.last_odd_time < self.position_expiry_age: ac.adsb_good = True else: ac.adsb_good = False # expire aircraft we have not seen for a while for ac in list(self.aircraft.values()): if (now - ac.last_message_time) > self.expiry_age: del self.aircraft[ac.icao] self.last_aircraft_update = now def send_aircraft_report(self): all_aircraft = {x.icao for x in self.aircraft.values() if x.messages > 1} seen_ac = all_aircraft.difference(self.reported) lost_ac = self.reported.difference(all_aircraft) if seen_ac: self.server.send_seen(seen_ac) if lost_ac: self.server.send_lost(lost_ac) self.reported = all_aircraft def send_rate_report(self, now): # report ADS-B position rate stats rate_report = {} for ac in self.aircraft.values(): interval = now - ac.rate_measurement_start if interval > 0 and ac.recent_adsb_positions > 0: rate = 1.0 * ac.recent_adsb_positions / interval ac.rate_measurement_start = now ac.recent_adsb_positions = 0 rate_report[ac.icao] = rate if rate_report: self.server.send_rate_report(rate_report) def periodic_stats(self, now): global_stats.log_and_reset(self) adsb_req = adsb_total = modes_req = modes_total = 0 now = monotonic_time() for ac in self.aircraft.values(): if ac.messages < 2: continue if ac.adsb_good: adsb_total += 1 if ac.requested: adsb_req += 1 else: modes_total += 1 if ac.requested: modes_req += 1 log('Aircraft: {modes_req} of {modes_total} Mode S, {adsb_req} of {adsb_total} ADS-B used', modes_req=modes_req, modes_total=modes_total, adsb_req=adsb_req, adsb_total=adsb_total) if self.recent_jumps > 0: log('Out-of-order timestamps: {recent}', recent=self.recent_jumps) self.recent_jumps = 0 # callbacks from server connection def server_connected(self): self.requested_traffic = set() self.requested_modeac = set() self.newly_seen = set() self.aircraft = {} self.reported = set() self.next_report = random.random() * self.report_interval if self.receiver.state != 'ready': self.receiver.reconnect() def server_disconnected(self): self.receiver.disconnect('Lost connection to multilateration server, no need for input data') self.next_report = None self.next_rate_report = None self.next_expiry = None def server_mlat_result(self, timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate, callsign, squawk, error_est, nstations, anon, modeac): global_stats.mlat_positions += 1 if anon and not self.allow_anon: return if modeac and not self.allow_modeac: return for o in self.outputs: o.send_position(timestamp, addr, lat, lon, alt, nsvel, ewvel, vrate, callsign, squawk, error_est, nstations, anon, modeac) def server_start_sending(self, icao_set, modeac_set=set()): for icao in icao_set: ac = self.aircraft.get(icao) if ac: ac.requested = True self.requested_traffic.update(icao_set) if self.allow_modeac: self.requested_modeac.update(modeac_set) self.update_receiver_filter() def server_stop_sending(self, icao_set, modeac_set=set()): for icao in icao_set: ac = self.aircraft.get(icao) if ac: ac.requested = False self.requested_traffic.difference_update(icao_set) if self.allow_modeac: self.requested_modeac.difference_update(modeac_set) self.update_receiver_filter() def update_receiver_filter(self): now = monotonic_time() mlat = set() for icao in self.requested_traffic: ac = self.aircraft.get(icao) if not ac or not ac.adsb_good: # requested, and we have not seen a recent ADS-B message from it mlat.add(icao) self.receiver.update_filter(mlat) self.receiver.update_modeac_filter(self.requested_modeac) # callbacks from receiver input def input_connected(self): self.server.send_input_connected() def input_disconnected(self): self.server.send_input_disconnected() # expire everything self.aircraft.clear() self.server.send_lost(self.reported) self.reported.clear() @mlat.profile.trackcpu def input_received_messages(self, messages): now = monotonic_time() for message in messages: handler = self.df_handlers.get(message.df) if handler: handler(message, now) # handlers for input messages def received_mode_change_event(self, message, now): # decoder mode changed, clock parameters possibly changed self.freq = message.eventdata['frequency'] self.recent_jumps = 0 self.server.send_clock_reset(reason='Decoder mode changed to {mode}'.format(mode=message.eventdata['mode']), frequency=message.eventdata['frequency'], epoch=message.eventdata['epoch'], mode=message.eventdata['mode']) log("Input format changed to {mode}, {freq:.0f}MHz clock", mode=message.eventdata['mode'], freq=message.eventdata['frequency']/1e6) def received_epoch_rollover_event(self, message, now): # epoch rollover, reset clock self.server.send_clock_reset('Epoch rollover detected') def received_timestamp_jump_event(self, message, now): self.recent_jumps += 1 self.server.send_clock_jump() #log("clockjump") if self.recent_jumps % 9 == 8 and time.monotonic() > self.last_jump_message + 300.0 : self.last_jump_message = time.monotonic() log("WARNING: the timestamps provided by your receiver do not seem to be self-consistent. " "This can happen if you feed data from multiple receivers to a single mlat-client, which " "is not supported; use a separate mlat-client for each receiver. " "Or you might have the wrong --input-type set, try radarcape_gps and dump1090.") def received_radarcape_position_event(self, message, now): lat, lon = message.eventdata['lat'], message.eventdata['lon'] if lat >= -90 and lat <= 90 and lon >= -180 and lon <= -180: self.server.send_position_update(lat, lon, message.eventdata['lon'], message.eventdata['alt'], 'egm96_meters') def received_df_misc(self, message, now): ac = self.aircraft.get(message.address) if not ac: return False # not a known ICAO ac.messages += 1 ac.last_message_time = now if ac.messages < 10: return # wait for more messages if not ac.requested: return # Candidate for MLAT if ac.adsb_good: return # reported position recently, no need for mlat self.server.send_mlat(message) def received_df11(self, message, now): ac = self.aircraft.get(message.address) if not ac: ac = Aircraft(message.address) ac.requested = (message.address in self.requested_traffic) ac.messages += 1 ac.last_message_time = now ac.rate_measurement_start = now self.aircraft[message.address] = ac return # will need some more messages.. ac.messages += 1 ac.last_message_time = now if ac.messages < 10: return # wait for more messages if not ac.requested: return # Candidate for MLAT if ac.adsb_good: return # reported position recently, no need for mlat self.server.send_mlat(message) def received_df17(self, message, now): ac = self.aircraft.get(message.address) if not ac: ac = Aircraft(message.address) ac.requested = (message.address in self.requested_traffic) ac.messages += 1 ac.last_message_time = now ac.rate_measurement_start = now self.aircraft[message.address] = ac return # wait for more messages ac.messages += 1 ac.last_message_time = now if ac.messages < 10: return if not message.even_cpr and not message.odd_cpr: # not a position message return if not message.valid: # invalid message return if message.even_cpr: ac.even_message = message else: ac.odd_message = message if not ac.even_message or not ac.odd_message: return if abs(ac.even_message.timestamp - ac.odd_message.timestamp) > 5 * self.freq: return if message.altitude is None: return # need an altitude if message.nuc < 6: return # need NUCp >= 6 ac.recent_adsb_positions += 1 if message.even_cpr: ac.last_even_time = now else: ac.last_odd_time = now if now - ac.last_even_time < self.position_expiry_age and now - ac.last_odd_time < self.position_expiry_age: ac.adsb_good = True else: ac.adsb_good = False if not ac.requested: return if self.server.send_split_sync: # this is a useful reference message self.server.send_split_sync(message) else: # this is a useful reference message pair self.server.send_sync(ac.even_message, ac.odd_message) def received_modeac(self, message, now): if message.address not in self.requested_modeac: return self.server.send_mlat(message) mlat-client-adsbfi/mlat/client/options.py0000644000175100017510000001535214702220435020232 0ustar debiandebian#!/usr/bin/env python3 # -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import argparse import functools import time import _modes from mlat.client.receiver import ReceiverConnection from mlat.client.output import OutputListener, OutputConnector from mlat.client.output import BasestationConnection, ExtBasestationConnection, BeastConnection from mlat.client.util import log _receiver_types = { # input type -> decoder mode, server clock type # the server clock type is used by the server to set # the clock jitter etc; clock frequency and # epoch are provided by the client. 'auto': (None, 'unknown'), 'dump1090': (_modes.BEAST, 'dump1090'), 'beast': (_modes.BEAST, 'beast'), 'radarcape_12mhz': (_modes.BEAST, 'radarcape_12mhz'), # compat 'radarcape_gps': (_modes.RADARCAPE, 'radarcape_gps'), # compat 'radarcape': (_modes.RADARCAPE, 'radarcape_gps'), # autodetects gps if present (doesn't work with intermediary decoder between mlat-cleint and radarcape, assume radarcape_gps) 'sbs': (_modes.SBS, 'sbs'), 'avrmlat': (_modes.AVRMLAT, 'unknown'), } def latitude(s): lat = float(s) if lat < -90 or lat > 90: raise argparse.ArgumentTypeError('Latitude %s must be in the range -90 to 90' % s) return lat def longitude(s): lon = float(s) if lon < -180 or lon > 360: raise argparse.ArgumentTypeError('Longitude %s must be in the range -180 to 360' % s) if lon > 180: lon -= 360 return lon def altitude(s): if s.endswith('m'): alt = float(s[:-1]) elif s.endswith('ft'): alt = float(s[:-2]) * 0.3048 else: alt = float(s) # Wikipedia to the rescue! # "The lowest point on dry land is the shore of the Dead Sea [...] # 418m below sea level". Perhaps not the best spot for a receiver? # La Rinconada, Peru, pop. 30,000, is at 5100m. if s == '60440ft': log('<3>Altitude not configured, please configure and reboot') time.sleep(3600) raise SystemExit if alt < -420 or alt > 5100: raise argparse.ArgumentTypeError('Altitude %s must be in the range -420m to 6000m' % s) return alt def port(s): port = int(s) if port < 1 or port > 65535: raise argparse.ArgumentTypeError('Port %s must be in the range 1 to 65535' % s) return port def hostport(s): parts = s.split(':') if len(parts) != 2: raise argparse.ArgumentTypeError("{} should be in 'host:port' format".format(s)) return (parts[0], int(parts[1])) def make_inputs_group(parser): inputs = parser.add_argument_group('Mode S receiver input connection') inputs.add_argument('--input-type', help="Sets the input receiver type.", choices=_receiver_types.keys(), default='dump1090') inputs.add_argument('--input-connect', help="host:port to connect to for Mode S traffic. Required.", required=True, type=hostport, default=('localhost', 30005)) def clock_frequency(args): return _modes.Reader(_receiver_types[args.input_type][0]).frequency def clock_epoch(args): return _modes.Reader(_receiver_types[args.input_type][0]).epoch def clock_type(args): return _receiver_types[args.input_type][1] def connection_mode(args): return _receiver_types[args.input_type][0] def make_results_group(parser): results = parser.add_argument_group('Results output') results.add_argument('--results', help=""" ,connect,host:port or ,listen,port. Protocol may be 'basestation', 'ext_basestation', or 'beast'. Can be specified multiple times.""", action='append', default=[]) results.add_argument("--no-anon-results", help="Do not generate results for anonymized aircraft", action='store_false', dest='allow_anon_results', default=True) results.add_argument("--no-modeac-results", help="Do not generate results for Mode A/C tracks", action='store_false', dest='allow_modeac_results', default=True) return results def output_factory(s): parts = s.split(',') if len(parts) != 3: raise ValueError('exactly three comma-separated values are needed (see help)') ctype, cmode, addr = parts connections = { 'basestation': BasestationConnection, 'ext_basestation': ExtBasestationConnection, 'beast': BeastConnection } c = connections.get(ctype) if c is None: raise ValueError("connection type '{0}' is not supported; options are: '{1}'".format( ctype, "','".join(connections.keys()))) if cmode == 'listen': return functools.partial(OutputListener, port=int(addr), connection_factory=c) elif cmode == 'connect': return functools.partial(OutputConnector, addr=hostport(addr), connection_factory=c) else: raise ValueError("connection mode '{0}' is not supported; options are: 'connect','listen'".format(cmode)) def build_outputs(args): outputs = [] for s in args.results: try: factory = output_factory(s) except ValueError as e: log("Warning: Ignoring bad results output option '{0}': {1}", s, str(e)) continue try: output = factory() except Exception as e: log("Warning: Could not create results output '{0}': {1}", s, str(e)) continue outputs.append(output) return outputs def build_receiver_connection(args): return ReceiverConnection(host=args.input_connect[0], port=args.input_connect[1], mode=connection_mode(args)) mlat-client-adsbfi/mlat/profile.py0000644000175100017510000000502014702220435016710 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- # Part of mlat-client - an ADS-B multilateration client. # Copyright 2015, Oliver Jowett # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program. If not, see . import os # NB: This requires Python 3.3 when MLAT_CPU_PROFILE is set. if not int(os.environ.get('MLAT_CPU_PROFILE', '0')): def trackcpu(f, **kwargs): return f def dump_cpu_profiles(): pass else: import sys import time import operator import functools _cpu_tracking = [] print('CPU profiling enabled', file=sys.stderr) def trackcpu(f, name=None, **kwargs): if name is None: name = f.__module__ + '.' + f.__qualname__ print('Profiling:', name, file=sys.stderr) tracking = [name, 0, 0.0] _cpu_tracking.append(tracking) @functools.wraps(f) def cpu_measurement_wrapper(*args, **kwargs): start = time.clock_gettime(time.CLOCK_THREAD_CPUTIME_ID) try: return f(*args, **kwargs) finally: end = time.clock_gettime(time.CLOCK_THREAD_CPUTIME_ID) tracking[1] += 1 tracking[2] += (end - start) return cpu_measurement_wrapper def dump_cpu_profiles(): print('{rank:4s} {name:60s} {count:6s} {total:8s} {each:8s}'.format( rank='#', name='Function', count='Calls', total='Total(s)', each='Each(us)'), file=sys.stderr) rank = 1 for name, count, total in sorted(_cpu_tracking, key=operator.itemgetter(2), reverse=True): if count == 0: break print('{rank:4d} {name:60s} {count:6d} {total:8.3f} {each:8.0f}'.format( rank=rank, name=name, count=count, total=total, each=total * 1e6 / count), file=sys.stderr) rank += 1 sys.stderr.flush() mlat-client-adsbfi/modes_reader.c0000644000175100017510000015405614702220435016554 0ustar debiandebian/* * Part of mlat-client - an ADS-B multilateration client. * Copyright 2015, Oliver Jowett * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "_modes.h" #include #include static unsigned long long monotic_ms(void) { struct timespec ts; unsigned long long mst; clock_gettime(CLOCK_MONOTONIC, &ts); mst = ((unsigned long long) ts.tv_sec) * 1000; mst += ts.tv_nsec / (1000 * 1000); return mst; } /* decoder modes */ typedef enum { DECODER_NONE, /* Not configured */ DECODER_BEAST, /* Beast binary, freerunning 48-bit timestamp @ 12MHz */ DECODER_RADARCAPE, /* Beast binary, 1GHz Radarcape timestamp, UTC synchronized from GPS */ DECODER_RADARCAPE_EMULATED, /* Beast binary, 1GHz Radarcape timestamp, not synchronized */ DECODER_AVR, /* AVR, no timestamp */ DECODER_AVRMLAT, /* AVR, freerunning 48-bit timestamp @ 12MHz */ DECODER_SBS, /* Kinetic SBS, freerunning 20MHz 24-bit timestamp, wraps around all the time but we try to widen it */ } decoder_mode; /* A timestamp that indicates the data is synthetic, created from a * multilateration result. (FF 00 "MLAT") */ #define MAGIC_MLAT_TIMESTAMP 0xFF004D4C4154ULL #define MAGIC_UAT_TIMESTAMP 0xFF004D4C4155ULL #define OUTLIER_LIMIT 1 /* a modesreader object */ typedef struct { PyObject_HEAD /* decoder characteristics */ decoder_mode decoder_mode; const char *decoder_mode_string; unsigned long long frequency; const char *epoch; unsigned long long last_timestamp; /* last seen timestamp */ unsigned long long last_ts_mono; /* system time associated with last timestamp */ unsigned long long monotonic; /* current monotonic time */ unsigned int radarcape_utc_bugfix; /* count timestamp outliers, first one is ignored / message discarded / last_timestamp not updated */ /* two consecutive outliers will result in sending a clock_reset message to the mlat-server (all sync dropped) */ /* a non outlier message will outliers to zero */ unsigned int outliers; unsigned long long outlierNoSpam; unsigned int outlier_accumulator; int try_toggle_freq; /* configurable bits */ char allow_mode_change; char want_zero_timestamps; char want_mlat_messages; char want_invalid_messages; char want_events; /* filtering */ PyObject *seen; PyObject *default_filter; PyObject *specific_filter; PyObject *modeac_filter; /* stats */ unsigned int received_messages; unsigned int suppressed_messages; unsigned int mlat_messages; } modesreader; /* methods for the modesreader type */ static PyObject *modesreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds); static int modesreader_init(modesreader *self, PyObject *args, PyObject *kwds); static void modesreader_dealloc(modesreader *self); static int modesreader_setmode(modesreader *self, PyObject *mode, void *dummy); static PyObject *modesreader_getmode(modesreader *self, void *dummy); static PyObject *modesreader_feed(modesreader *self, PyObject *args, PyObject *kwds); /* modesreader fields */ static PyMemberDef modesreaderMembers[] = { /* these two are derived from the current mode always */ { "frequency", T_ULONGLONG, offsetof(modesreader, frequency), READONLY, "timestamp frequency" }, { "epoch", T_STRING, offsetof(modesreader, epoch), READONLY, "timestamp epoch" }, { "last_timestamp", T_ULONGLONG, offsetof(modesreader, last_timestamp), 0, "last timestamp seen" }, { "allow_mode_change", T_BOOL, offsetof(modesreader, allow_mode_change), 0, "can the decoder change mode based on status messages it receives?" }, { "want_zero_timestamps", T_BOOL, offsetof(modesreader, want_zero_timestamps), 0, "should the decoder return messages with zero timestamps?" }, { "want_mlat_messages", T_BOOL, offsetof(modesreader, want_mlat_messages), 0, "should the decoder return synthetic mlat messages?" }, { "want_invalid_messages", T_BOOL, offsetof(modesreader, want_invalid_messages), 0, "should the decoder return invalid messages?" }, { "want_events", T_BOOL, offsetof(modesreader, want_events), 0, "should the decoder return metadata events?" }, { "seen", T_OBJECT, offsetof(modesreader, seen), 0, "set of addresses seen by the decoder" }, { "default_filter", T_OBJECT, offsetof(modesreader, default_filter), 0, "DF accept filter for all aircraft"}, { "specific_filter", T_OBJECT, offsetof(modesreader, specific_filter), 0, "DF accept filter for specific aircraft"}, { "modeac_filter", T_OBJECT, offsetof(modesreader, modeac_filter), 0, "Mode A/C accept filter"}, { "received_messages", T_UINT, offsetof(modesreader, received_messages), 0, "total number of messages decoded"}, { "suppressed_messages", T_UINT, offsetof(modesreader, suppressed_messages), 0, "number of messages suppressed by filtering"}, { "mlat_messages", T_UINT, offsetof(modesreader, mlat_messages), 0, "number of incoming MLAT messages received (and ignored)"}, { NULL, 0, 0, 0, NULL } }; /* .. and the mode field which has a special getter/setter */ static PyGetSetDef modesreaderGetSet[] = { { "mode", (getter)modesreader_getmode, (setter)modesreader_setmode, "decoder mode", NULL }, { NULL, NULL, NULL, NULL, NULL } }; /* modesreader methods */ static PyMethodDef modesreaderMethods[] = { { "feed", (PyCFunction)modesreader_feed, METH_VARARGS|METH_KEYWORDS, "Process and decode some data." }, { NULL, NULL, 0, NULL } }; /* modesreader type definition */ static PyTypeObject modesreaderType = { PyVarObject_HEAD_INIT(NULL, 0) "_modes.Reader", /* tp_name */ sizeof(modesreader), /* tp_basicsize */ 0, /* tp_itemsize */ (destructor)modesreader_dealloc, /* tp_dealloc */ 0, /* tp_print */ 0, /* tp_getattr */ 0, /* tp_setattr */ 0, /* tp_reserved */ 0, /* tp_repr */ 0, /* tp_as_number */ 0, /* tp_as_sequence */ 0, /* tp_as_mapping */ 0, /* tp_hash */ 0, /* tp_call */ 0, /* tp_str */ PyObject_GenericGetAttr, /* tp_getattro */ PyObject_GenericSetAttr, /* tp_setattro */ 0, /* tp_as_buffer */ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE, /* tp_flags */ "A ModeS stream reader.", /* tp_doc */ 0, /* tp_traverse */ 0, /* tp_clear */ 0, /* tp_richcompare */ 0, /* tp_weaklistoffset */ 0, /* tp_iter */ 0, /* tp_iternext */ modesreaderMethods, /* tp_methods */ modesreaderMembers, /* tp_members */ modesreaderGetSet, /* tp_getset */ 0, /* tp_base */ 0, /* tp_dict */ 0, /* tp_descr_get */ 0, /* tp_descr_set */ 0, /* tp_dictoffset */ (initproc)modesreader_init, /* tp_init */ 0, /* tp_alloc */ modesreader_new, /* tp_new */ }; /* lookup table for decoder_mode <-> python strings */ static struct { decoder_mode mode; const char *cstr; PyObject *pystr; } modetable[] = { { DECODER_BEAST, "BEAST", NULL }, { DECODER_RADARCAPE, "RADARCAPE", NULL }, { DECODER_RADARCAPE_EMULATED, "RADARCAPE_EMULATED", NULL }, { DECODER_AVR, "AVR", NULL }, { DECODER_AVRMLAT, "AVRMLAT", NULL }, { DECODER_SBS, "SBS", NULL }, { DECODER_NONE, NULL, NULL } }; /* internal helpers */ static PyObject *feed_beast(modesreader *self, Py_buffer *buf, int max_messages); static PyObject *feed_avr(modesreader *self, Py_buffer *buf, int max_messages); static PyObject *feed_sbs(modesreader *self, Py_buffer *buf, int max_messages); static void set_decoder_mode(modesreader *self, decoder_mode newmode); static PyObject *radarcape_settings_to_list(uint8_t settings); static PyObject *radarcape_status_to_dict(uint8_t *message); static int filter_message(modesreader *self, PyObject *message); /* * module setup/teardown */ int modesreader_module_init(PyObject *m) { int i; if (PyType_Ready(&modesreaderType) < 0) goto error; for (i = 0; modetable[i].cstr != NULL; ++i) { PyObject *pystr = PyUnicode_FromString(modetable[i].cstr); if (pystr == NULL) { goto error; } Py_INCREF(pystr); modetable[i].pystr = pystr; if (PyModule_AddObject(m, modetable[i].cstr, pystr) < 0) goto error; } Py_INCREF(&modesreaderType); if (PyModule_AddObject(m, "Reader", (PyObject *)&modesreaderType) < 0) { Py_DECREF(&modesreaderType); goto error; } return 0; error: for (i = 0; modetable[i].cstr != NULL; ++i) { Py_CLEAR(modetable[i].pystr); } return -1; } void modesreader_module_free(PyObject *m) { int i; for (i = 0; modetable[i].cstr != NULL; ++i) { Py_CLEAR(modetable[i].pystr); } } static PyObject *modesreader_new(PyTypeObject *type, PyObject *args, PyObject *kwds) { modesreader *self; self = (modesreader *)type->tp_alloc(type, 0); if (self == NULL) return NULL; /* minimal init */ set_decoder_mode(self, DECODER_NONE); self->last_timestamp = 0; self->last_ts_mono = 0; self->monotonic = 0; self->outliers = 0; self->allow_mode_change = 1; self->want_zero_timestamps = 0; self->want_mlat_messages = 0; self->want_invalid_messages = 0; self->want_events = 1; Py_INCREF(Py_None); self->seen = Py_None; Py_INCREF(Py_None); self->default_filter = Py_None; Py_INCREF(Py_None); self->specific_filter = Py_None; Py_INCREF(Py_None); self->modeac_filter = Py_None; self->received_messages = self->suppressed_messages = self->mlat_messages = 0; return (PyObject *)self; } static void modesreader_dealloc(modesreader *self) { Py_CLEAR(self->seen); Py_CLEAR(self->default_filter); Py_CLEAR(self->specific_filter); Py_CLEAR(self->modeac_filter); Py_TYPE(self)->tp_free((PyObject*)self); } static int modesreader_init(modesreader *self, PyObject *args, PyObject *kwds) { static char *kwlist[] = { "mode", NULL }; PyObject *mode = Py_None; if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O", kwlist, &mode)) return -1; if (modesreader_setmode(self, mode, NULL) < 0) return -1; return 0; } static int modesreader_setmode(modesreader *self, PyObject *mode, void *dummy) { int i; if (mode == Py_None) { set_decoder_mode(self, DECODER_NONE); return 0; } for (i = 0; modetable[i].cstr != NULL; ++i) { int res = PyObject_RichCompareBool(modetable[i].pystr, mode, Py_EQ); if (res < 0) return -1; if (res == 1) { set_decoder_mode(self, modetable[i].mode); break; } } if (modetable[i].cstr == NULL) { PyErr_SetString(PyExc_ValueError, "unrecognized decoder mode"); return -1; } return 0; } static PyObject *modesreader_getmode(modesreader *self, void *dummy) { int i; for (i = 0; modetable[i].cstr; ++i) { if (self->decoder_mode == modetable[i].mode) { Py_INCREF(modetable[i].pystr); return modetable[i].pystr; } } Py_INCREF(Py_None); return Py_None; } /* feed some data to the reader and does one of: * 1) returns a tuple (bytes_consumed, messages, error_pending), or * 2) throws an exception * * If a stream error is seen, but some messages were parsed OK, * then an exception is not immediately thrown and the parsed * messages are returned with error_pending = True. The caller * should call feed again (after consuming the given number of * bytes) to get the exception. * * Internal errors (e.g. out of memory) are thrown immediately. */ static PyObject *modesreader_feed(modesreader *self, PyObject *args, PyObject *kwds) { Py_buffer buffer; PyObject *rv = NULL; int max_messages = 0; static char *kwlist[] = { "buffer", "max_messages", NULL }; if (!PyArg_ParseTupleAndKeywords(args, kwds, "y*|i", kwlist, &buffer, &max_messages)) return NULL; if (buffer.itemsize != 1) { PyErr_SetString(PyExc_ValueError, "buffer itemsize is not 1"); goto out; } if (!PyBuffer_IsContiguous(&buffer, 'C')) { PyErr_SetString(PyExc_ValueError, "buffer is not contiguous"); goto out; } switch (self->decoder_mode) { case DECODER_NONE: PyErr_SetString(PyExc_NotImplementedError, "decoder mode is None, no decoder type selected"); break; case DECODER_BEAST: case DECODER_RADARCAPE: case DECODER_RADARCAPE_EMULATED: rv = feed_beast(self, &buffer, max_messages); break; case DECODER_AVR: case DECODER_AVRMLAT: rv = feed_avr(self, &buffer, max_messages); break; case DECODER_SBS: rv = feed_sbs(self, &buffer, max_messages); break; default: PyErr_Format(PyExc_AssertionError, "decoder somehow got into illegal mode %d", (int)self->decoder_mode); break; } out: PyBuffer_Release(&buffer); return rv; } static void set_decoder_mode(modesreader *self, decoder_mode newmode) { self->decoder_mode = newmode; switch (newmode) { case DECODER_BEAST: self->frequency = 12000000ULL; /* assumed */ self->epoch = NULL; break; case DECODER_RADARCAPE: self->frequency = 1000000000ULL; self->epoch = "utc_midnight"; break; case DECODER_RADARCAPE_EMULATED: self->frequency = 1000000000ULL; self->epoch = NULL; break; case DECODER_AVRMLAT: self->frequency = 12000000ULL; /* assumed */ self->epoch = NULL; break; case DECODER_SBS: self->frequency = 20000000ULL; self->epoch = NULL; break; case DECODER_AVR: default: self->frequency = 0; self->epoch = NULL; break; } } /* turn a radarcape DIP switch setting byte into a Python list of settings strings */ static PyObject *radarcape_settings_to_list(uint8_t settings) { return Py_BuildValue("[s,s,s,s,s,s,s]", settings & 0x01 ? "beast" : (settings & 0x04 ? "avrmlat" : "avr"), settings & 0x02 ? "filtered_frames" : "all_frames", settings & 0x08 ? "no_crc" : "check_crc", settings & 0x10 ? "gps_timestamps" : "legacy_timestamps", settings & 0x20 ? "rtscts" : "no_rtscts", settings & 0x40 ? "no_fec" : "fec", settings & 0x80 ? "modeac" : "no_modeac"); } /* turn a radarcape GPS status byte into a Python dict */ static PyObject *radarcape_gpsstatus_to_dict(uint8_t status) { if (!(status & 0x80)) { return Py_BuildValue("{s:O,s:O}", "utc_bugfix", Py_False, "timestamp_ok", Py_True ); } return Py_BuildValue("{s:O,s:O,s:O,s:O,s:O,s:O,s:O}", "utc_bugfix", Py_True, "timestamp_ok", (status & 0x20 ? Py_False : Py_True), "sync_ok", (status & 0x10 ? Py_True : Py_False), "utc_offset_ok", (status & 0x08 ? Py_True : Py_False), "sats_ok", (status & 0x04 ? Py_True : Py_False), "tracking_ok", (status & 0x02 ? Py_True : Py_False), "antenna_ok", (status & 0x01 ? Py_True : Py_False)); } /* turn a radarcape 0x34 status message into a Python dict */ static PyObject *radarcape_status_to_dict(uint8_t *message) { return Py_BuildValue("{s:N,s:i,s:N}", "settings", radarcape_settings_to_list(message[0]), "timestamp_pps_delta", (int)(int8_t)message[1], "gps_status", radarcape_gpsstatus_to_dict(message[2])); } /* create an event message for a timestamp jump */ static PyObject *make_timestamp_jump_event(modesreader *self, unsigned long long timestamp) { PyObject *eventdata = Py_BuildValue("{s:K}", "last-timestamp", self->last_timestamp); if (eventdata == NULL) return NULL; return modesmessage_new_eventmessage(DF_EVENT_TIMESTAMP_JUMP, timestamp, eventdata); } /* create an event message for a decoder mode change. the new mode should already be set. */ static PyObject *make_mode_change_event(modesreader *self) { PyObject *eventdata = Py_BuildValue("{s:N,s:K,s:s}", "mode", modesreader_getmode(self, NULL), "frequency", self->frequency, "epoch", self->epoch); if (eventdata == NULL) return NULL; return modesmessage_new_eventmessage(DF_EVENT_MODE_CHANGE, 0, eventdata); } /* create an event message for an epoch rollover (e.g. GPS end of day) */ static PyObject *make_epoch_rollover_event(modesreader *self, unsigned long long timestamp) { PyObject *eventdata = PyDict_New(); if (eventdata == NULL) return NULL; return modesmessage_new_eventmessage(DF_EVENT_EPOCH_ROLLOVER, timestamp, eventdata); } /* create an event message for a radarcape status report */ static PyObject *make_radarcape_status_event(modesreader *self, unsigned long long timestamp, uint8_t *data) { PyObject *eventdata = radarcape_status_to_dict(data); if (eventdata == NULL) return NULL; return modesmessage_new_eventmessage(DF_EVENT_RADARCAPE_STATUS, timestamp, eventdata); } /* create an event message for a radarcape position report */ static PyObject *radarcape_position_to_dict(uint8_t *data) { float lat, lon, alt; #if PY_MAJOR_VERSION >= 3 && PY_MINOR_VERSION >=11 lat = PyFloat_Unpack4(data + 4, 1); if (lat == -1.0 && PyErr_Occurred()) return NULL; lon = PyFloat_Unpack4(data + 8, 1); if (lon == -1.0 && PyErr_Occurred()) return NULL; alt = PyFloat_Unpack4(data + 12, 1); if (alt == -1.0 && PyErr_Occurred()) return NULL; #else lat = _PyFloat_Unpack4(data + 4, 1); if (lat == -1.0 && PyErr_Occurred()) return NULL; lon = _PyFloat_Unpack4(data + 8, 1); if (lon == -1.0 && PyErr_Occurred()) return NULL; alt = _PyFloat_Unpack4(data + 12, 1); if (alt == -1.0 && PyErr_Occurred()) return NULL; #endif return Py_BuildValue("{s:f,s:f,s:f}", "lat", lat, "lon", lon, "alt", alt); } static PyObject *make_radarcape_position_event(modesreader *self, uint8_t *data) { PyObject *eventdata = radarcape_position_to_dict(data); if (eventdata == NULL) return NULL; return modesmessage_new_eventmessage(DF_EVENT_RADARCAPE_POSITION, 0, eventdata); } static int is_synthetic_timestamp(unsigned long long timestamp) { return (timestamp == 0 || (timestamp >= MAGIC_MLAT_TIMESTAMP && timestamp <= MAGIC_MLAT_TIMESTAMP + 10)); } /* check if the given timestamp is in range (not a jump), return 1 if it is */ static int timestamp_check(modesreader *self, unsigned long long timestamp) { if (is_synthetic_timestamp(timestamp)) return 1; if (self->frequency == 0) return 1; self->monotonic = monotic_ms(); // update system time if (self->last_timestamp == 0) return 1; long long ts_elapsed = (long long) timestamp - (long long) self->last_timestamp; long long sys_elapsed = (self->monotonic - self->last_ts_mono) * (self->frequency / 1000); long long max_offset = 1.25 * self->frequency; // 1.25 seconds if (ts_elapsed > sys_elapsed + max_offset || ts_elapsed < sys_elapsed - max_offset) { self->outliers++; if (self->outliers > OUTLIER_LIMIT) { if (self->monotonic > self->outlierNoSpam) { double tosec = 1.0 / self->frequency; fprintf(stderr, "outlier detected with ts: %.3f, last_ts: %.3f, ts_elapsed: %.3f, sys_elapsed: %.3f (values in seconds)\n", timestamp * tosec, self->last_timestamp * tosec, ts_elapsed * tosec, sys_elapsed * tosec); self->outlier_accumulator = 0; self->outlierNoSpam = self->monotonic + 5000; } else { self->outlier_accumulator++; if (self->outlier_accumulator > 100) { // try switching to another input type // disable frequency toggling ... bad idea //self->try_toggle_freq++; self->outlier_accumulator = 0; } } } return 0; } self->outliers = 0; return 1; } /* update self->last_timestamp given that we just saw this timestamp */ static void timestamp_update(modesreader *self, unsigned long long timestamp) { if (is_synthetic_timestamp(timestamp)) { /* special timestamps, don't use them */ return; } if (self->last_timestamp == 0 || self->frequency == 0) { /* startup cases, just accept whatever */ self->last_ts_mono = self->monotonic; self->last_timestamp = timestamp; return; } if (self->last_timestamp > timestamp && (self->last_timestamp - timestamp) < 90 * self->frequency) { /* ignore small moves backwards */ return; } if ((self->decoder_mode == DECODER_RADARCAPE || self->decoder_mode == DECODER_RADARCAPE_EMULATED) && timestamp >= (86340 * 1000000000ULL) && self->last_timestamp <= (60 * 1000000000ULL)) { /* in radarcape mode, don't allow last_timestamp to roll back to the previous day * as we will have already issued an epoch reset */ return; } // don't update the timestamp for outliers until we exceed OUTLIER_LIMIT if (self->outliers && self->outliers <= OUTLIER_LIMIT) return; self->last_timestamp = timestamp; self->last_ts_mono = self->monotonic; } /* feed implementation for Beast-format data (including Radarcape) */ static PyObject *feed_beast(modesreader *self, Py_buffer *buffer, int max_messages) { PyObject *rv = NULL; uint8_t *buffer_start, *p, *eod; int message_count = 0; PyObject *message_tuple = NULL; PyObject **messages = NULL; int error_pending = 0; buffer_start = buffer->buf; if (max_messages <= 0) { /* allocate the maximum size we might need, given a minimal encoding of: * <1A> <'1'> <6 bytes timestamp> <1 byte signal> <2 bytes message> = 11 bytes total */ max_messages = buffer->len / 11 + 2; } messages = calloc(max_messages, sizeof(PyObject*)); if (!messages) { PyErr_NoMemory(); goto out; } /* parse messages */ p = buffer_start; eod = buffer_start + buffer->len; while (p+2 <= eod && message_count+2 < max_messages) { int message_len = -1; uint64_t timestamp; uint8_t signal; uint8_t data[14]; uint8_t *m, *eom; int i; uint8_t type; PyObject *message; int wanted; int has_timestamp_signal; if (p[0] != 0x1a) { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a 0x1A marker at offset %d but found 0x%02x instead", (int) (p - buffer_start), (int)p[0]); goto out; } has_timestamp_signal = 1; type = p[1]; switch (type) { case '1': message_len = 2; break; /* mode A/C */ case '2': message_len = 7; break; /* mode S short */ case '3': message_len = 14; break; /* mode S long */ case '4': message_len = 14; break; /* radarcape status message */ case '5': /* radarcape position message, no timestamp/signal bytes */ message_len = 21; has_timestamp_signal = 0; break; default: error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected message type 0x%02x after 0x1A marker at offset %d", (int)p[1], (int) (p - buffer_start)); goto out; } m = p + 2; eom = m + message_len + (has_timestamp_signal ? 7 : 0); if (eom > eod) break; #define ADVANCE \ do { \ if (*m++ == 0x1a) { \ if (m < eod && *m != 0x1a) { \ error_pending = 1; \ if (message_count > 0) \ goto nomoredata; \ PyErr_SetString(PyExc_ValueError, "Lost sync with input stream: expected 0x1A after 0x1A escape"); \ goto out; \ } \ ++m, ++eom; \ if (eom > eod) \ goto nomoredata; \ } \ } while(0) if (has_timestamp_signal) { /* timestamp, 6 bytes */ timestamp = *m; ADVANCE; timestamp = (timestamp << 8) | *m; ADVANCE; timestamp = (timestamp << 8) | *m; ADVANCE; timestamp = (timestamp << 8) | *m; ADVANCE; timestamp = (timestamp << 8) | *m; ADVANCE; timestamp = (timestamp << 8) | *m; ADVANCE; /* signal, 1 byte */ signal = *m; ADVANCE; } else { timestamp = 0; signal = 0; } /* message, N bytes */ for (i = 0; i < message_len; ++i) { data[i] = *m; ADVANCE; } /* do some filtering */ if (type == '4') { /* radarcape-style status message, use this to switch our decoder type */ self->radarcape_utc_bugfix = (data[2] & 0x80) == 0x80; if (self->allow_mode_change) { decoder_mode newmode; if (data[0] & 0x10) { /* radarcape in GPS timestamp mode */ if ((data[2] & 0x20) == 0x20) { newmode = DECODER_RADARCAPE_EMULATED; } else { newmode = DECODER_RADARCAPE; } } else { /* radarcape in 12MHz timestamp mode */ newmode = DECODER_BEAST; } /* handle mode changes by inserting an event message */ if (newmode != self->decoder_mode) { set_decoder_mode(self, newmode); if (self->want_events) { if (! (messages[message_count++] = make_mode_change_event(self))) goto out; } } } } // hacky: toggle mode if self->try_toggle_freq was set in a function if (self->try_toggle_freq > 0) { self->try_toggle_freq = -5; decoder_mode newmode = DECODER_NONE; if (self->decoder_mode == DECODER_BEAST) { newmode = DECODER_RADARCAPE; } if (self->decoder_mode == DECODER_RADARCAPE) { newmode = DECODER_BEAST; } if (newmode != DECODER_NONE) { set_decoder_mode(self, newmode); if (self->want_events) { if (! (messages[message_count++] = make_mode_change_event(self))) goto out; } } } // ignore ModeAC messages if (type == '1') { /* don't try to process this as a Mode S message */ p = m; continue; } if (has_timestamp_signal && !is_synthetic_timestamp(timestamp)) { if (self->decoder_mode == DECODER_BEAST) { /* 12MHz mode */ /* check for very out of range value * (dump1090 can hold messages for up to 60 seconds! so be conservative here) * also work around dump1090-mutability issue #47 which can send very stale Mode A/C messages */ if (self->want_events && type != '1' && !timestamp_check(self, timestamp)) { if (self->outliers > OUTLIER_LIMIT && ! (messages[message_count++] = make_timestamp_jump_event(self, timestamp))) goto out; } /* adjust the timestamps so they always reflect the start of the frame */ uint64_t adjust; if (type == '1') { // Mode A/C, timestamp reported at F2 which is 20.3us after F1 // this is 243.6 cycles at 12MHz adjust = 244; } else if (type == '2') { // Mode S short, timestamp reported at end of frame, frame is 8us preamble plus 56us data // this is 768 cycles at 12MHz adjust = 768; } else if (type == '3') { // Mode S long, timestamp reported halfway through the frame (at bit 56), same offset as Mode S short adjust = 768; } else { // anything else we assume is already correct adjust = 0; } if (timestamp < adjust) { timestamp = 0; } else { timestamp = timestamp - adjust; } } else { /* gps mode */ /* adjust timestamp so that it is a contiguous nanoseconds-since- * midnight value, rather than the raw form which skips values once * a second */ uint64_t nanos = timestamp & 0x00003FFFFFFF; uint64_t secs = timestamp >> 30; if (!self->radarcape_utc_bugfix) { /* fix up the timestamp so it is UTC, not 1 second ahead */ if (secs == 0) { secs = 86399; } else { --secs; } } timestamp = nanos + secs * 1000000000; /* adjust the timestamps so they always reflect the start of the frame */ uint64_t adjust; if (type == '1') { // Mode A/C, timestamp reported at F2 which is 20.3us after F1 adjust = 20300; } else if (type == '2') { // Mode S short, timestamp reported at end of frame, frame is 8us preamble plus 56us data adjust = 64000; } else if (type == '3') { // Mode S long, timestamp reported at end of frame, frame is 8us preamble plus 112us data adjust = 120000; } else { // anything else we assume is already correct adjust = 0; } if (adjust <= timestamp) { timestamp = timestamp - adjust; } else { /* wrap it to the previous day */ timestamp = timestamp + 86400 * 1000000000ULL - adjust; } /* check for end of day rollover */ if (self->want_events && self->last_timestamp >= (86340 * 1000000000ULL) && timestamp <= (60 * 1000000000ULL)) { if (! (messages[message_count++] = make_epoch_rollover_event(self, timestamp))) goto out; } else if (self->want_events && type != '1' && !timestamp_check(self, timestamp)) { if (! (messages[message_count++] = make_timestamp_jump_event(self, timestamp))) goto out; } } if (type != '1') { timestamp_update(self, timestamp); } } if (type == '4') { /* radarcape-style status message, emit the status event if wanted */ if (self->want_events) { if (! (messages[message_count++] = make_radarcape_status_event(self, timestamp, data))) goto out; } /* don't try to process this as a Mode S message */ p = m; continue; } if (type == '5') { /* radarcape-style position message, emit the position event if wanted */ if (self->want_events) { if (! (messages[message_count++] = make_radarcape_position_event(self, data))) goto out; } /* don't try to process this as a Mode S message */ p = m; continue; } /* it's a Mode A/C or Mode S message, parse it */ if (! (message = modesmessage_from_buffer(timestamp, signal, data, message_len))) goto out; /* apply filters, update seen-set */ ++self->received_messages; wanted = filter_message(self, message); if (wanted < 0) goto out; else if (wanted) messages[message_count++] = message; else { ++self->suppressed_messages; Py_DECREF(message); } p = m; } nomoredata: if (! (message_tuple = PyTuple_New(message_count))) goto out; while (--message_count >= 0) { PyTuple_SET_ITEM(message_tuple, message_count, messages[message_count]); /* steals ref */ } rv = Py_BuildValue("(l,N,N)", (long) (p - buffer_start), message_tuple, PyBool_FromLong(error_pending)); out: while (--message_count >= 0) { Py_XDECREF(messages[message_count]); } free(messages); return rv; } /********** SBS INPUT **************/ /* * Some notes on this format, as it is poorly documented by Kinetic: * * The stream can start at an arbitrary point, the first byte might be mid-packet. * You need to look for a DLE STX to synchronize with the stream. * This implementation does that in the Python code to keep this bit simpler; the * C code assumes it is always given bytes starting at the start of a packet. * * You might get arbitrary packet types e.g. AIS interleaved with Mode S messages. * This implementation doesn't try to interpret them at all, it just reads all * data until DLE ETX regardless of type and skips those types it doesn't * understand. * * The Mode S CRC values are not the raw bytes from the message; they are the * residual CRC value after XORing the raw bytes with the calculated CRC over * the body of the message. That is, a DF17 message with a correct CRC will have * zeros in the CRC bytes; a DF11 with correct CRC will have the IID in the CRC * bytes; messages that use Address/Parity will have the address in the CRC bytes. * To recover the original message, calculate the CRC and XOR it back into the CRC * bytes. Andrew Whewell says this is probably controlled by a Basestation setting. * * The timestamps are measured at the _end_ of the frame, not at the start. * As frames are variable length, if you want a timestamp anchored to the * start of the frame (as dump1090 / Beast do), you have to compensate for * the frame length. */ static PyObject *feed_sbs(modesreader *self, Py_buffer *buffer, int max_messages) { PyObject *rv = NULL; uint8_t *buffer_start, *p, *eod; int message_count = 0; PyObject *message_tuple = NULL; PyObject **messages = NULL; int error_pending = 0; buffer_start = buffer->buf; if (max_messages <= 0) { /* allocate the maximum size we might need, given a minimal encoding of: * <0x09> <3 bytes timestamp> <2 bytes message> <2 bytes CRC> = 13 bytes total */ max_messages = buffer->len / 13 + 1; } messages = calloc(max_messages, sizeof(PyObject*)); if (!messages) { PyErr_NoMemory(); goto out; } /* parse messages */ p = buffer_start; eod = buffer_start + buffer->len; while (p+13 <= eod && message_count < max_messages) { int message_len = -1; uint64_t timestamp; /* largest message we care about is: * type 1 byte 0x05 = ADS-B * spare 1 byte * timestamp 3 bytes * data 14 bytes * total 19 bytes */ uint8_t data[19]; uint8_t *m; int i; uint8_t type; uint32_t crc; PyObject *message; if (p[0] != 0x10 || p[1] != 0x02) { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected DLE STX at offset %d but found 0x%02x 0x%02x instead", (int) (p - buffer_start), (int)p[0], (int)p[1]); goto out; } /* scan for DLE ETX, copy data */ m = p + 2; i = 0; while (m < eod) { if (*m == 0x10) { /* DLE */ if ((m+1) >= eod) goto nomoredata; if (m[1] == 0x03) { /* DLE ETX */ break; } if (m[1] != 0x10) { /* DLE */ error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected DLE 0x%02x at offset %d", (int) (m - buffer_start), (int)m[1]); goto out; } /* DLE DLE */ ++m; } if (i < 19) data[i++] = *m; ++m; } /* now pointing at DLE of DLE ETX */ m += 2; /* first CRC byte */ if (m >= eod) goto nomoredata; if (*m++ == 0x10) { if (m >= eod) goto nomoredata; if (m[0] != 0x10) { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected DLE 0x%02x at offset %d", (int) (m - buffer_start), (int)*m); goto out; } ++m; } /* second CRC byte */ if (m >= eod) goto nomoredata; if (*m++ == 0x10) { if (m >= eod) goto nomoredata; if (m[0] != 0x10) { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected DLE 0x%02x at offset %d", (int) (m - buffer_start), (int)*m); goto out; } ++m; } /* try to make sense of the message */ type = data[0]; switch (type) { case 0x01: /* ADS-B or TIS-B */ message_len = 14; break; case 0x05: /* Mode S, long */ message_len = 14; break; case 0x07: /* Mode S, short */ message_len = 7; break; case 0x09: /* Mode A/C */ message_len = 2; break; default: /* something else, skip it */ p = m; continue; } if ((5 + message_len) > i) { /* not enough data */ p = m; continue; } /* regenerate message CRC */ crc = modescrc_buffer_crc(&data[5], message_len - 3); data[5 + message_len - 3] ^= crc >> 16; data[5 + message_len - 2] ^= crc >> 8; data[5 + message_len - 1] ^= crc; /* little-endian, apparently */ timestamp = (data[4] << 16) | (data[3] << 8) | (data[2]); /* Baseless speculation! Let's assume that it's like the Radarcape * and measures at the end of the frame. * * It's easier to add to the timestamp than subtract from it, so * add on enough of an offset so that the timestamps we report are * consistently (start of frame + 112us) regardless of the actual * frame length. */ timestamp = (timestamp + ((14-message_len) * 160)) & 0xFFFFFF; /* we don't use timestamp_update or timestamp_check here because SBS is "special" */ /* The SBS timestamp is only 24 bits wide; at 20MHz this overflows more than once * a second (about every 839ms). To get a useful timestamp for mlat synchronization, * we have to widen the timestamp. * * It wasn't reliable to do this based on the system clock, there are enough * unpredictable delays between the SBS and mlat-client that it didn't work well. * Instead, we assume that we will be receiving at least one message per 839ms. * so if we ever see a timestamp that has gone backwards, it must be due to * exactly one overflow of the timestamp counter. * * This is usually true in cases where we see enough traffic for mlat/sync. When it * isn't true, you will get synchronization jumps that are a multiple of 839ms. */ /* merge in top bits of the current widened counter */ timestamp = timestamp | (self->last_timestamp & 0xFFFFFFFFFF000000ULL); /* check for rollover, if it happened then increase the widened part */ if (timestamp < self->last_timestamp) timestamp += (1 << 24); self->last_timestamp = timestamp; /* decode it */ if (! (message = modesmessage_from_buffer(timestamp, 0, &data[5], message_len))) goto out; /* apply filters, update seen-set */ ++self->received_messages; int wanted = filter_message(self, message); if (wanted < 0) goto out; else if (wanted) messages[message_count++] = message; else { ++self->suppressed_messages; Py_DECREF(message); } p = m; } nomoredata: if (! (message_tuple = PyTuple_New(message_count))) goto out; while (--message_count >= 0) { PyTuple_SET_ITEM(message_tuple, message_count, messages[message_count]); /* steals ref */ } rv = Py_BuildValue("(l,N,N)", (long) (p - buffer_start), message_tuple, PyBool_FromLong(error_pending)); out: while (--message_count >= 0) { Py_XDECREF(messages[message_count]); } free(messages); return rv; } /********** AVR INPUT **************/ static int hexvalue(char c) { if (c >= '0' && c <= '9') return c - '0'; else if (c >= 'a' && c <= 'f') return c - 'a' + 10; else if (c >= 'A' && c <= 'F') return c - 'A' + 10; else return -1; } static PyObject *feed_avr(modesreader *self, Py_buffer *buffer, int max_messages) { PyObject *rv = NULL; uint8_t *buffer_start, *p, *eod; int message_count = 0; PyObject *message_tuple = NULL; PyObject **messages = NULL; int error_pending = 0; buffer_start = buffer->buf; if (max_messages <= 0) { /* allocate the maximum size we might need, given a minimal encoding of: * '*' <2 bytes message> ';' LF */ max_messages = buffer->len / 5 + 1; } messages = calloc(max_messages, sizeof(PyObject*)); if (!messages) { PyErr_NoMemory(); goto out; } p = buffer_start; eod = buffer_start + buffer->len; while (p+17 <= eod && message_count+1 < max_messages) { int message_len = -1; uint64_t timestamp; uint8_t data[14]; uint8_t message_format; int i; uint8_t *m; PyObject *message; message_format = p[0]; if (message_format != '@' && message_format != '%' && message_format != '<' && message_format != '*' && message_format != ':') { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected '@'/'%%'/'<'/'*'/':' at offset %d but found 0x%02x instead", (int) (p - buffer_start), (int)p[0]); goto out; } m = p + 1; if (message_format == '@' || message_format == '%' || message_format == '<') { /* read 6 bytes of timestamp */ timestamp = 0; for (i = 0; i < 12; ++i, ++m) { int c; if (m >= eod) { goto nomoredata; } timestamp <<= 4; c = hexvalue(*m); if (c >= 0) { timestamp |= c; } else { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead", (int) (m - buffer_start), (int)*m); goto out; } } } else { /* AVR format with no timestamp */ timestamp = 0; } if (message_format == '<') { /* in format '<', skip 1 byte of signal */ m += 2; if (m >= eod) goto nomoredata; } /* read 2-14 bytes of data */ message_len = 0; while (message_len < 14) { int c0, c1; if (m+1 >= eod) { goto nomoredata; } if (m[0] == ';') { break; /* end of message marker */ } else { c0 = hexvalue(m[0]); if (c0 < 0) { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead", (int) (m - buffer_start), (int)m[0]); goto out; } } c1 = hexvalue(m[1]); if (c1 < 0) { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected a hex digit at offset %d but found 0x%02x instead", (int) (m - buffer_start), (int)m[1]); goto out; } if (message_len < 14) { data[message_len] = (c0 << 4) | c1; } ++message_len; m += 2; } /* consume ';' */ if (m >= eod) goto nomoredata; if (*m != ';') { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: expected ';' at offset %d but found 0x%02x instead", (int) (m - buffer_start), (int)*m); goto out; } /* CR LF, LF CR, LF all seen! ugh. */ /* skip until CR or LF */ while (m < eod && *m != '\r' && *m != '\n') ++m; /* consume however many CRs and LFs */ while (m < eod && (*m == '\r' || *m == '\n')) ++m; /* check length */ if (message_len != 2 && message_len != 7 && message_len != 14) { error_pending = 1; if (message_count > 0) goto nomoredata; PyErr_Format(PyExc_ValueError, "Lost sync with input stream: unexpected %d-byte message starting at offset %d", message_len, (int) (p - buffer_start)); goto out; } /* check for very out of range value * (dump1090 can hold messages for up to 60 seconds! so be conservative here) * also work around dump1090-mutability issue #47 which can send very stale Mode A/C messages */ if (self->want_events && message_len != 2 && !timestamp_check(self, timestamp)) { if (! (messages[message_count++] = make_timestamp_jump_event(self, timestamp))) goto out; } timestamp_update(self, timestamp); /* decode it */ if (! (message = modesmessage_from_buffer(timestamp, 0, data, message_len))) goto out; /* apply filters, update seen-set */ ++self->received_messages; int wanted = filter_message(self, message); if (wanted < 0) goto out; else if (wanted) messages[message_count++] = message; else { ++self->suppressed_messages; Py_DECREF(message); } /* next message */ p = m; } nomoredata: if (! (message_tuple = PyTuple_New(message_count))) goto out; while (--message_count >= 0) { PyTuple_SET_ITEM(message_tuple, message_count, messages[message_count]); /* steals ref */ } rv = Py_BuildValue("(l,N,N)", (long) (p - buffer_start), message_tuple, PyBool_FromLong(error_pending)); out: while (--message_count >= 0) { Py_XDECREF(messages[message_count]); } free(messages); return rv; } /* inspect a message, update the seen set * return 1 if we should pass this message on to the caller * return 0 if we should drop it * return -1 on internal error (exception has been raised) */ static int filter_message(modesreader *self, PyObject *o) { modesmessage *message = (modesmessage *)o; // Check this, first. We don't really want to use MLAT msgs... if (message->timestamp == MAGIC_MLAT_TIMESTAMP && !self->want_mlat_messages) { ++self->mlat_messages; return 0; } // Drop messages as long as timestamps are jumping. if (self->outliers > 0) return 0; // Ignore messages that jump backwards if (self->last_timestamp > message->timestamp) return 0; if (message->df == DF_MODEAC) { if (self->modeac_filter != NULL && self->modeac_filter != Py_None) { return PySequence_Contains(self->modeac_filter, message->address); } return 1; } if (!message->valid) { return self->want_invalid_messages; /* don't process further, contents are dubious */ } if (self->seen != NULL && self->seen != Py_None) { if (message->df == 11 || message->df == 17 || message->df == 18) { /* note that we saw this aircraft, even if the message is filtered. * only do this for CRC-checked messages as we get a lot of noise * otherwise. */ if (PySet_Add(self->seen, message->address) < 0) { return -1; } } } if (message->timestamp == 0 && !self->want_zero_timestamps) { return 0; } if ((self->default_filter == NULL || self->default_filter == Py_None) && (self->specific_filter == NULL || self->specific_filter == Py_None)) { /* no filters installed, match everything */ return 1; } /* check per-type filters */ if (self->default_filter != NULL && self->default_filter != Py_None) { int rv; PyObject *entry = PySequence_GetItem(self->default_filter, message->df); if (entry == NULL) return -1; rv = PyObject_IsTrue(entry); Py_DECREF(entry); if (rv != 0) return rv; } if (self->specific_filter != NULL && self->specific_filter != Py_None) { int rv; PyObject *entry = PySequence_GetItem(self->specific_filter, message->df); if (entry == NULL) return -1; if (entry == Py_None) { rv = 0; } else { rv = PySequence_Contains(entry, message->address); } Py_DECREF(entry); if (rv != 0) return rv; } return 0; } mlat-client-adsbfi/_modes.c0000644000175100017510000000443514702220435015364 0ustar debiandebian/* * Part of mlat-client - an ADS-B multilateration client. * Copyright 2015, Oliver Jowett * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "_modes.h" /* would be nice to move this into the submodule init, but that needs python 3.5 for PyModule_AddFunctions */ static PyMethodDef methods[] = { { "crc", modescrc_crc, METH_VARARGS, "Calculate the Mode S CRC over a buffer. Don't include the message's trailing CRC bytes in the provided buffer." }, { "EventMessage", (PyCFunction)modesmessage_eventmessage, METH_VARARGS|METH_KEYWORDS, "Constructs a new event message with a given type, timestamp, and event data." }, { NULL, NULL, 0, NULL } }; static void free_modes(PyObject *); PyDoc_STRVAR(docstr, "C helpers to speed up ModeS message processing"); static PyModuleDef module = { PyModuleDef_HEAD_INIT, "_modes", /* m_name */ docstr, /* m_doc */ -1, /* m_size */ methods, /* m_methods */ NULL, /* m_slots / m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ (freefunc)free_modes /* m_free */ }; PyMODINIT_FUNC PyInit__modes(void) { PyObject *m = NULL; m = PyModule_Create(&module); if (m == NULL) return NULL; if (modescrc_module_init(m) < 0) { goto error; } if (modesmessage_module_init(m) < 0) { goto error; } if (modesreader_module_init(m) < 0) { goto error; } return m; error: Py_DECREF(m); return NULL; } void free_modes(PyObject *m) { modesreader_module_free(m); modesmessage_module_free(m); modescrc_module_free(m); } mlat-client-adsbfi/flightaware/0000755000175100017510000000000014702220435016241 5ustar debiandebianmlat-client-adsbfi/flightaware/__init__.py0000644000175100017510000000000014702220435020340 0ustar debiandebianmlat-client-adsbfi/flightaware/client/0000755000175100017510000000000014702220435017517 5ustar debiandebianmlat-client-adsbfi/flightaware/client/__init__.py0000644000175100017510000000000014702220435021616 0ustar debiandebianmlat-client-adsbfi/flightaware/client/adeptclient.py0000644000175100017510000004040214702220435022365 0ustar debiandebian# -*- mode: python; indent-tabs-mode: nil -*- """ The FlightAware adept protocol, client side. """ import asyncore import socket import errno import sys import itertools import struct from mlat.client import net, util, stats, version # UDP protocol submessages # TODO: This needs merging with mlat-client's variant # (they are not quite identical so it'll need a new # udp protocol version - this version has the decoded # ICAO address at the start of MLAT/SYNC to ease the # work of the server doing fan-out) TYPE_SYNC = 1 TYPE_MLAT_SHORT = 2 TYPE_MLAT_LONG = 3 # TYPE_SSYNC = 4 TYPE_REBASE = 5 TYPE_ABS_SYNC = 6 TYPE_MLAT_MODEAC = 7 STRUCT_HEADER = struct.Struct(">IHQ") STRUCT_SYNC = struct.Struct(">B3Bii14s14s") # STRUCT_SSYNC = struct.Struct(">Bi14s") STRUCT_MLAT_SHORT = struct.Struct(">B3Bi7s") STRUCT_MLAT_LONG = struct.Struct(">B3Bi14s") STRUCT_REBASE = struct.Struct(">BQ") STRUCT_ABS_SYNC = struct.Struct(">B3BQQ14s14s") STRUCT_MLAT_MODEAC = struct.Struct(">Bi2s") if sys.platform == 'linux': IP_MTU = 14 # not defined in the socket module, unfortunately def get_mtu(s): try: return s.getsockopt(socket.SOL_IP, IP_MTU) except OSError: return None except socket.error: return None else: def get_mtu(s): return None class UdpServerConnection: def __init__(self, host, port, key): self.host = host self.port = port self.key = key self.base_timestamp = None self.header_timestamp = None self.buf = bytearray(1500) self.used = 0 self.seq = 0 self.count = 0 self.sock = None self.mtu = 1400 self.route_mtu = -1 def start(self): addrlist = socket.getaddrinfo(host=self.host, port=self.port, family=socket.AF_UNSPEC, type=socket.SOCK_DGRAM, proto=0, flags=socket.AI_NUMERICHOST) if len(addrlist) != 1: # expect exactly one result since we specify AI_NUMERICHOST raise IOError('unexpectedly got {0} results when resolving {1}'.format(len(addrlist), self.host)) a_family, a_type, a_proto, a_canonname, a_sockaddr = addrlist[0] self.sock = socket.socket(a_family, a_type, a_proto) self.remote_address = a_sockaddr self.refresh_socket() def refresh_socket(self): try: self.sock.connect(self.remote_address) except OSError: pass except socket.error: pass new_mtu = get_mtu(self.sock) if new_mtu is not None and new_mtu != self.route_mtu: util.log('Route MTU changed to {0}', new_mtu) self.route_mtu = new_mtu self.mtu = max(100, self.route_mtu - 100) def prepare_header(self, timestamp): self.base_timestamp = timestamp STRUCT_HEADER.pack_into(self.buf, 0, self.key, self.seq, self.base_timestamp) self.used += STRUCT_HEADER.size def rebase(self, timestamp): self.base_timestamp = timestamp STRUCT_REBASE.pack_into(self.buf, self.used, TYPE_REBASE, self.base_timestamp) self.used += STRUCT_REBASE.size def send_mlat(self, message): if not self.used: self.prepare_header(message.timestamp) delta = message.timestamp - self.base_timestamp if abs(delta) > 0x7FFFFFF0: self.rebase(message.timestamp) delta = 0 if len(message) == 2: STRUCT_MLAT_MODEAC.pack_into(self.buf, self.used, TYPE_MLAT_MODEAC, delta, bytes(message)) self.used += STRUCT_MLAT_MODEAC.size elif len(message) == 7: STRUCT_MLAT_SHORT.pack_into(self.buf, self.used, TYPE_MLAT_SHORT, message.address >> 16, (message.address >> 8) & 255, message.address & 255, delta, bytes(message)) self.used += STRUCT_MLAT_SHORT.size elif len(message) == 14: STRUCT_MLAT_LONG.pack_into(self.buf, self.used, TYPE_MLAT_LONG, message.address >> 16, (message.address >> 8) & 255, message.address & 255, delta, bytes(message)) self.used += STRUCT_MLAT_LONG.size if self.used > self.mtu: self.flush() def send_sync(self, em, om): if not self.used: self.prepare_header(int((em.timestamp + om.timestamp) / 2)) if abs(em.timestamp - om.timestamp) > 0xFFFFFFF0: # use abs sync STRUCT_ABS_SYNC.pack_into(self.buf, self.used, TYPE_ABS_SYNC, em.address >> 16, (em.address >> 8) & 255, em.address & 255, em.timestamp, om.timestamp, bytes(em), bytes(om)) self.used += STRUCT_ABS_SYNC.size else: edelta = em.timestamp - self.base_timestamp odelta = om.timestamp - self.base_timestamp if abs(edelta) > 0x7FFFFFF0 or abs(odelta) > 0x7FFFFFF0: self.rebase(int((em.timestamp + om.timestamp) / 2)) edelta = em.timestamp - self.base_timestamp odelta = om.timestamp - self.base_timestamp STRUCT_SYNC.pack_into(self.buf, self.used, TYPE_SYNC, em.address >> 16, (em.address >> 8) & 255, em.address & 255, edelta, odelta, bytes(em), bytes(om)) self.used += STRUCT_SYNC.size if self.used > self.mtu: self.flush() def flush(self): if not self.used: return try: self.sock.send(memoryview(self.buf)[0:self.used]) except socket.error: pass stats.global_stats.server_udp_bytes += self.used self.used = 0 self.base_timestamp = None self.seq = (self.seq + 1) & 0xffff self.count += 1 if self.count % 50 == 0: self.refresh_socket() def close(self): self.used = 0 if self.sock: self.sock.close() def __str__(self): return '{0}:{1}'.format(self.host, self.port) class AdeptReader(asyncore.file_dispatcher, net.LoggingMixin): """Reads tab-separated key-value messages from stdin and dispatches them.""" def __init__(self, connection, coordinator): super().__init__(sys.stdin) self.connection = connection self.coordinator = coordinator self.partial_line = b'' self.closed = False self.handlers = { 'mlat_wanted': self.process_wanted_message, 'mlat_unwanted': self.process_unwanted_message, 'mlat_result': self.process_result_message, 'mlat_status': self.process_status_message } def readable(self): return True def writable(self): return False def handle_read(self): try: moredata = self.recv(16384) except socket.error as e: if e.errno == errno.EAGAIN: return raise if not moredata: self.close() return stats.global_stats.server_rx_bytes += len(moredata) data = self.partial_line + moredata lines = data.split(b'\n') for line in lines[:-1]: try: self.process_line(line.decode('ascii')) except IOError: raise except Exception: util.log_exc('Unexpected exception processing adept message') self.partial_line = lines[-1] def handle_close(self): self.close() def close(self): if not self.closed: self.closed = True super().close() self.connection.disconnect() def process_line(self, line): fields = line.split('\t') message = dict(zip(fields[0::2], fields[1::2])) handler = self.handlers.get(message['type']) if handler: handler(message) def parse_hexid_list(self, s): icao = set() modeac = set() if s != '': for x in s.split(' '): if x[0] == '@': modeac.add(int(x[1:], 16)) else: icao.add(int(x, 16)) return icao, modeac def process_wanted_message(self, message): wanted_icao, wanted_modeac = self.parse_hexid_list(message['hexids']) self.coordinator.server_start_sending(wanted_icao, wanted_modeac) def process_unwanted_message(self, message): unwanted_icao, unwanted_modeac = self.parse_hexid_list(message['hexids']) self.coordinator.server_stop_sending(unwanted_icao, unwanted_modeac) def process_result_message(self, message): self.coordinator.server_mlat_result(timestamp=None, addr=int(message['hexid'], 16), lat=float(message['lat']), lon=float(message['lon']), alt=float(message['alt']), nsvel=float(message['nsvel']), ewvel=float(message['ewvel']), vrate=float(message['fpm']), callsign=None, squawk=None, error_est=None, nstations=None, anon=bool(message.get('anon', 0)), modeac=bool(message.get('modeac', 0))) def process_status_message(self, message): s = message.get('status', 'unknown') r = int(message.get('receiver_sync_count', 0)) if s == 'ok': self.connection.state = "synchronized with {} nearby receivers".format(r) elif s == 'unstable': self.connection.state = "clock unstable" elif s == 'no_sync': self.connection.state = "not synchronized with any nearby receivers" else: self.connection.state = "{} {}".format(s, r) class AdeptWriter(asyncore.file_dispatcher, net.LoggingMixin): """Writes tab-separated key-value messages to stdout.""" def __init__(self, connection): super().__init__(sys.stdout) self.connection = connection self.writebuf = bytearray() self.closed = False self.last_position = None def readable(self): return False def writable(self): return len(self.writebuf) > 0 def handle_write(self): if self.writebuf: sent = self.send(self.writebuf) del self.writebuf[:sent] stats.global_stats.server_tx_bytes += sent if len(self.writebuf) > 65536: raise IOError('Server write buffer overflow (too much unsent data)') def handle_close(self): self.close() def close(self): if not self.closed: self.closed = True super().close() self.connection.disconnect() def send_message(self, **kwargs): line = '\t'.join(itertools.chain.from_iterable(kwargs.items())) + '\n' self.writebuf += line.encode('ascii') def send_seen(self, aclist): self.send_message(type='mlat_seen', hexids=' '.join('{0:06X}'.format(icao) for icao in aclist)) def send_lost(self, aclist): self.send_message(type='mlat_lost', hexids=' '.join('{0:06X}'.format(icao) for icao in aclist)) def send_rate_report(self, report): self.send_message(type='mlat_rates', rates=' '.join('{0:06X} {1:.2f}'.format(icao, rate) for icao, rate in report.items())) def send_ready(self, allow_anon, allow_modeac): capabilities = [] if allow_anon: capabilities.append('anon') if allow_modeac: capabilities.append('modeac') self.send_message(type='mlat_event', event='ready', mlat_client_version=version.CLIENT_VERSION, capabilities=' '.join(capabilities)) def send_input_connected(self): self.send_message(type='mlat_event', event='connected') def send_input_disconnected(self): self.send_message(type='mlat_event', event='disconnected') def send_clock_reset(self, reason, frequency=None, epoch=None, mode=None): message = { 'type': 'mlat_event', 'event': 'clock_reset', 'reason': reason } if frequency is not None: message['frequency'] = str(frequency) message['epoch'] = 'none' if epoch is None else epoch message['mode'] = mode self.send_message(**message) def send_position_update(self, lat, lon, alt, altref): new_pos = (lat, lon, alt, altref) if self.last_position is None or self.last_position != new_pos: self.send_message(type='mlat_location_update', lat='{0:.5f}'.format(lat), lon='{0:.5f}'.format(lon), alt='{0:.0f}'.format(alt), altref=altref) self.last_position = new_pos def send_udp_report(self, count): self.send_message(type='mlat_udp_report', messages_sent=str(count)) class AdeptConnection: UDP_REPORT_INTERVAL = 60.0 def __init__(self, udp_transport=None, allow_anon=True, allow_modeac=True): if udp_transport is None: raise NotImplementedError('non-UDP transport not supported') self.reader = None self.writer = None self.coordinator = None self.closed = False self.udp_transport = udp_transport self.allow_anon = allow_anon self.allow_modeac = allow_modeac self.state = 'init' def start(self, coordinator): self.coordinator = coordinator self.reader = AdeptReader(self, coordinator) self.writer = AdeptWriter(self) self.udp_transport.start() self.send_mlat = self.udp_transport.send_mlat self.send_sync = self.udp_transport.send_sync self.send_split_sync = None self.send_seen = self.writer.send_seen self.send_lost = self.writer.send_lost self.send_rate_report = self.writer.send_rate_report self.send_clock_reset = self.writer.send_clock_reset self.send_input_connected = self.writer.send_input_connected self.send_input_disconnected = self.writer.send_input_disconnected self.send_position_update = self.writer.send_position_update self.state = 'connected' self.writer.send_ready(allow_anon=self.allow_anon, allow_modeac=self.allow_modeac) self.next_udp_report = util.monotonic_time() + self.UDP_REPORT_INTERVAL self.coordinator.server_connected() def disconnect(self, why=None): if not self.closed: self.closed = True self.state = 'closed' if self.reader: self.reader.close() if self.writer: self.writer.close() if self.udp_transport: self.udp_transport.close() if self.coordinator: self.coordinator.server_disconnected() def heartbeat(self, now): if self.udp_transport: self.udp_transport.flush() if now > self.next_udp_report: self.next_udp_report = now + self.UDP_REPORT_INTERVAL self.writer.send_udp_report(self.udp_transport.count)