11 Commits

Author SHA1 Message Date
junzis
7a62d1dbfb add api docs 2016-08-16 16:22:13 +02:00
junzis
2f89d1a95c update README, add position_with_ref() 2016-08-16 15:56:05 +02:00
junzis
2fccacd724 update position decoding, handle surface position messages, error fix in vertical rate calculation. 2016-08-16 14:33:31 +02:00
junzis
556e499064 minor update of cprNL function 2016-07-08 17:53:42 +02:00
junzis
5518816b32 simplify N/NL functions in position decoding 2016-07-08 17:44:18 +02:00
junzis
faf43134e5 separate position decoding to airborne and surface types 2016-07-08 14:59:45 +02:00
Junzi Sun
4666de403d Merge pull request #3 from astrofrog/python3
Fix imports for Python 3
2016-07-07 17:22:35 +02:00
Thomas Robitaille
a196d673df Fix imports for Python 3 2016-06-28 22:12:08 +01:00
junzis
8ef02fa2b1 release 1.0.4 2016-03-23 14:00:53 +01:00
junzis
72f2bcd275 update README 2016-03-23 11:45:38 +01:00
junzis
1ccd4fd83b update CRC function 2016-03-23 11:35:20 +01:00
12 changed files with 849 additions and 139 deletions

View File

@@ -41,17 +41,35 @@ Usage
import pyModeS as pms
Common function for Mode-S message:
.. code:: python
pms.df(msg) # Downlink Format
pms.crc(msg, encode=False) # Perform CRC or generate parity bit
pms.hex2bin(str) # Convert hexadecimal string to binary string
pms.bin2int(str) # Convert binary string to integer
pms.hex2int(str) # Convert hexadecimal string to integer
Core functions for ADS-B decoding:
.. code:: python
pms.adsb.icao(msg)
pms.adsb.callsign(msg)
pms.adsb.position(msg_odd, msg_even, t_odd, t_even)
pms.adsb.position(msg_even, msg_odd, t_even, t_odd)
pms.adsb.position_with_ref(msg, lat_ref, lon_ref)
pms.adsb.altitude(msg)
pms.adsb.velocity(msg)
pms.adsb.speed_heading(msg)
**Hint: When you have a fix position of the aircraft or you know the
location of your receiver, it is convinent to use `position_with_ref()` method
to decode with only one position message (either odd or even)**
Core functions for EHS decoding:
.. code:: python

3
doc/.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
_build
_static
_templates

225
doc/Makefile Normal file
View File

@@ -0,0 +1,225 @@
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " applehelp to make an Apple Help Book"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " epub3 to make an epub3"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " xml to make Docutils-native XML files"
@echo " pseudoxml to make pseudoxml-XML files for display purposes"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
@echo " coverage to run coverage check of the documentation (if enabled)"
@echo " dummy to check syntax errors of document sources"
.PHONY: clean
clean:
rm -rf $(BUILDDIR)/*
.PHONY: html
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
.PHONY: dirhtml
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
.PHONY: singlehtml
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
.PHONY: pickle
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
.PHONY: json
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
.PHONY: htmlhelp
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
.PHONY: qthelp
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pyModeS.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pyModeS.qhc"
.PHONY: applehelp
applehelp:
$(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
@echo
@echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
@echo "N.B. You won't be able to view it unless you put it in" \
"~/Library/Documentation/Help or install it in your application" \
"bundle."
.PHONY: devhelp
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/pyModeS"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pyModeS"
@echo "# devhelp"
.PHONY: epub
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
.PHONY: epub3
epub3:
$(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3
@echo
@echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3."
.PHONY: latex
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
.PHONY: latexpdf
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: latexpdfja
latexpdfja:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through platex and dvipdfmx..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
.PHONY: text
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
.PHONY: man
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
.PHONY: texinfo
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
.PHONY: info
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
.PHONY: gettext
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
.PHONY: changes
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
.PHONY: linkcheck
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
.PHONY: doctest
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
.PHONY: coverage
coverage:
$(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
@echo "Testing of coverage in the sources finished, look at the " \
"results in $(BUILDDIR)/coverage/python.txt."
.PHONY: xml
xml:
$(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
@echo
@echo "Build finished. The XML files are in $(BUILDDIR)/xml."
.PHONY: pseudoxml
pseudoxml:
$(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
@echo
@echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
.PHONY: dummy
dummy:
$(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy
@echo
@echo "Build finished. Dummy builder generates no files."

337
doc/conf.py Normal file
View File

@@ -0,0 +1,337 @@
# -*- coding: utf-8 -*-
#
# pyModeS documentation build configuration file, created by
# sphinx-quickstart on Tue Aug 16 15:47:05 2016.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#
# import os
# import sys
# sys.path.insert(0, os.path.abspath('.'))
# -- General configuration ------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#
# needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.coverage',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
# The encoding of source files.
#
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'pyModeS'
# General information about the project.
project = u'pyModeS'
copyright = u'2016, Junzi Sun'
author = u'Junzi Sun'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = u'1.0.5'
# The full version, including alpha/beta/rc tags.
release = u'1.0.5'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#
# This is also used if you do content translation via gettext catalogs.
# Usually you set "language" from the command line for these cases.
language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#
# today = ''
#
# Else, today_fmt is used as the format for a strftime call.
#
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This patterns also effect to html_static_path and html_extra_path
exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
# The reST default role (used for this markup: `text`) to use for all
# documents.
#
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
# keep_warnings = False
# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = True
# -- Options for HTML output ----------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = 'alabaster'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
# html_theme_path = []
# The name for this set of Sphinx documents.
# "<project> v<release> documentation" by default.
#
# html_title = u'pyModeS v1.0.5'
# A shorter title for the navigation bar. Default is the same as html_title.
#
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#
# html_logo = None
# The name of an image file (relative to this directory) to use as a favicon of
# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
# Add any extra paths that contain custom files (such as robots.txt or
# .htaccess) here, relative to this directory. These files are copied
# directly to the root of the documentation.
#
# html_extra_path = []
# If not None, a 'Last updated on:' timestamp is inserted at every page
# bottom, using the given strftime format.
# The empty string is equivalent to '%b %d, %Y'.
#
# html_last_updated_fmt = None
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#
# html_additional_pages = {}
# If false, no module index is generated.
#
# html_domain_indices = True
# If false, no index is generated.
#
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
# html_file_suffix = None
# Language to be used for generating the HTML full-text search index.
# Sphinx supports the following languages:
# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
#
# html_search_language = 'en'
# A dictionary with options for the search language support, empty by default.
# 'ja' uses this config value.
# 'zh' user can custom change `jieba` dictionary path.
#
# html_search_options = {'type': 'default'}
# The name of a javascript file (relative to the configuration directory) that
# implements a search results scorer. If empty, the default will be used.
#
# html_search_scorer = 'scorer.js'
# Output file base name for HTML help builder.
htmlhelp_basename = 'pyModeSdoc'
# -- Options for LaTeX output ---------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',
# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'pyModeS.tex', u'pyModeS Documentation',
u'Junzi Sun', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#
# latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#
# latex_use_parts = False
# If true, show page references after internal links.
#
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#
# latex_appendices = []
# If false, no module index is generated.
#
# latex_domain_indices = True
# -- Options for manual page output ---------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'pymodes', u'pyModeS Documentation',
[author], 1)
]
# If true, show URL addresses after external links.
#
# man_show_urls = False
# -- Options for Texinfo output -------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'pyModeS', u'pyModeS Documentation',
author, 'pyModeS', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#
# texinfo_appendices = []
# If false, no module index is generated.
#
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#
# texinfo_no_detailmenu = False

36
doc/pyModeS.rst Normal file
View File

@@ -0,0 +1,36 @@
.. pyModeS documentation master file, created by
sphinx-quickstart on Tue Aug 16 15:47:05 2016.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
pyModeS API documents
=====================
pyModeS.adsb module
-------------------
.. automodule:: pyModeS.adsb
:members:
:undoc-members:
:show-inheritance:
pyModeS.ehs module
------------------
.. automodule:: pyModeS.ehs
:members:
:undoc-members:
:show-inheritance:
pyModeS.util module
-------------------
.. automodule:: pyModeS.util
:members:
:undoc-members:
:show-inheritance:

1
doc/requirements.txt Normal file
View File

@@ -0,0 +1 @@
pyModeS==1.0.5

View File

@@ -1,3 +1,5 @@
from util import hex2bin, bin2int, hex2int, df
import adsb
import ehs
from __future__ import absolute_import, print_function, division
from .util import *
from . import adsb
from . import ehs

View File

@@ -18,37 +18,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import math
import util
def checksum(msg):
"""CRC check the ADS-B message
Args:
msg (string): 28 bytes hexadecimal message string
Returns:
bool: Checksum passed or not
"""
if len(msg) == 28:
offset = 0
elif len(msg) == 14:
offset = 112-56
else:
# raise exception
return False
msgbin = util.hex2bin(msg)
checksum = int(msg[22:28], 16)
crc = 0
for i in xrange(len(msgbin)):
# print msgbin[i]
if int(msgbin[i]):
crc ^= util.MODES_CHECKSUM_TABLE[i+offset]
if crc == checksum:
return True
else:
return False
from . import util
from .util import crc
def df(msg):
@@ -182,7 +153,18 @@ def cprlon(msg):
def position(msg0, msg1, t0, t1):
"""Decode position from the combination of even and odd position message
if (5 <= typecode(msg0) <= 8 and 5 <= typecode(msg1) <= 8):
return surface_position(msg0, msg1, t0, t1)
elif (9 <= typecode(msg0) <= 18 and 9 <= typecode(msg1) <= 18):
return airborne_position(msg0, msg1, t0, t1)
else:
raise RuntimeError("incorrect or inconsistant message types")
def airborne_position(msg0, msg1, t0, t1):
"""Decode airborn position from a pair of even and odd position message
131072 is 2^17, since CPR lat and lon are 17 bits each.
Args:
msg0 (string): even message (28 bytes hexadecimal string)
@@ -192,11 +174,6 @@ def position(msg0, msg1, t0, t1):
Returns:
(float, float): (latitude, longitude) of the aircraft
"""
if typecode(msg0) < 5 or typecode(msg0) > 18:
raise RuntimeError("%s: Not a position message" % msg0)
if typecode(msg1) < 5 or typecode(msg1) > 18:
raise RuntimeError("%s: Not a position message" % msg1)
msgbin0 = util.hex2bin(msg0)
msgbin1 = util.hex2bin(msg1)
@@ -210,7 +187,7 @@ def position(msg0, msg1, t0, t1):
air_d_lat_odd = 360.0 / 59
# compute latitude index 'j'
j = int(math.floor(59 * cprlat_even - 60 * cprlat_odd + 0.5))
j = util.floor(59 * cprlat_even - 60 * cprlat_odd + 0.5)
lat_even = float(air_d_lat_even * (j % 60 + cprlat_even))
lat_odd = float(air_d_lat_odd * (j % 59 + cprlat_odd))
@@ -227,14 +204,14 @@ def position(msg0, msg1, t0, t1):
# compute ni, longitude index m, and longitude
if (t0 > t1):
ni = _cprN(lat_even, 0)
m = math.floor(cprlon_even * (_cprNL(lat_even)-1) -
ni = max(_cprNL(lat_even), 1)
m = util.floor(cprlon_even * (_cprNL(lat_even)-1) -
cprlon_odd * _cprNL(lat_even) + 0.5)
lon = (360.0 / ni) * (m % ni + cprlon_even)
lat = lat_even
else:
ni = _cprN(lat_odd, 1)
m = math.floor(cprlon_even * (_cprNL(lat_odd)-1) -
ni = max(_cprNL(lat_odd) - 1, 1)
m = util.floor(cprlon_even * (_cprNL(lat_odd)-1) -
cprlon_odd * _cprNL(lat_odd) + 0.5)
lon = (360.0 / ni) * (m % ni + cprlon_odd)
lat = lat_odd
@@ -245,22 +222,116 @@ def position(msg0, msg1, t0, t1):
return round(lat, 5), round(lon, 5)
def _cprN(lat, is_odd):
nl = _cprNL(lat) - is_odd
return nl if nl > 1 else 1
def position_with_ref(msg, lat_ref, lon_ref):
if 5 <= typecode(msg) <= 8:
return airborne_position_with_ref(msg, lat_ref, lon_ref)
elif 9 <= typecode(msg) <= 18:
return surface_position_with_ref(msg, lat_ref, lon_ref)
else:
raise RuntimeError("incorrect or inconsistant message types")
def airborne_position_with_ref(msg, lat_ref, lon_ref):
"""Decode airborn position with one message,
knowing previous reference location
Args:
msg (string): even message (28 bytes hexadecimal string)
lat_ref: previous known latitude
lon_ref: previous known longitude
Returns:
(float, float): (latitude, longitude) of the aircraft
"""
i = oe_flag(msg)
d_lat = 360.0/59 if i else 360.0/60
msgbin = util.hex2bin(msg)
cprlat = util.bin2int(msgbin[54:71]) / 131072.0
cprlon = util.bin2int(msgbin[71:88]) / 131072.0
j = util.floor(lat_ref / d_lat) \
+ util.floor(0.5 + ((lat_ref % d_lat) / d_lat) - cprlat)
lat = d_lat * (j + cprlat)
ni = _cprNL(lat) - i
if ni > 0:
d_lon = 360.0 / ni
else:
d_lon = 360.0
m = util.floor(lon_ref / d_lon) \
+ util.floor(0.5 + ((lon_ref % d_lon) / d_lon) - cprlon)
lon = d_lon * (m + cprlon)
return round(lat, 5), round(lon, 5)
def surface_position(msg0, msg1, t0, t1):
# TODO: implement surface positon
raise RuntimeError('suface position decoding to be implemented soon...')
def surface_position_with_ref(msg, lat_ref, lon_ref):
"""Decode surface position with one message,
knowing reference nearby location, such as previously calculated location,
ground station, or airport location, etc.
Args:
msg (string): even message (28 bytes hexadecimal string)
lat_ref: previous known latitude
lon_ref: previous known longitude
Returns:
(float, float): (latitude, longitude) of the aircraft
"""
i = oe_flag(msg)
d_lat = 90.0/59 if i else 90.0/60
msgbin = util.hex2bin(msg)
cprlat = util.bin2int(msgbin[54:71]) / 131072.0
cprlon = util.bin2int(msgbin[71:88]) / 131072.0
j = util.floor(lat_ref / d_lat) \
+ util.floor(0.5 + ((lat_ref % d_lat) / d_lat) - cprlat)
lat = d_lat * (j + cprlat)
ni = _cprNL(lat) - i
if ni > 0:
d_lon = 360.0 / ni
else:
d_lon = 360.0
m = util.floor(lon_ref / d_lon) \
+ util.floor(0.5 + ((lon_ref % d_lon) / d_lon) - cprlon)
lon = d_lon * (m + cprlon)
return round(lat, 5), round(lon, 5)
def _cprNL(lat):
try:
nz = 60
a = 1 - math.cos(math.pi * 2 / nz)
b = math.cos(math.pi / 180.0 * abs(lat)) ** 2
nl = 2 * math.pi / (math.acos(1 - a/b))
return int(nl)
except:
# happens when latitude is +/-90 degree
if lat == 0:
return 59
if lat == 87 or lat == -87:
return 2
if lat > 87 or lat < -87:
return 1
nz = 15
a = 1 - math.cos(math.pi / (2 * nz))
b = math.cos(math.pi / 180.0 * abs(lat)) ** 2
nl = 2 * math.pi / (math.acos(1 - a/b))
NL = util.floor(nl)
return NL
def altitude(msg):
"""Decode aircraft altitude
@@ -373,8 +444,8 @@ def velocity(msg):
tag = 'AS'
vr_sign = util.bin2int(msgbin[68])
vr = util.bin2int(msgbin[68:77]) # vertical rate
rocd = -1*vr if vr_sign else vr # rate of climb/descend
vr = util.bin2int(msgbin[69:78]) # vertical rate
rocd = -1*vr if vr_sign else vr # rate of climb/descend
return int(spd), round(hdg, 1), int(rocd), tag

View File

@@ -17,30 +17,8 @@ You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import util
def crc(msg):
"""Calculate the cyclic redundancy checksum of an message
Args:
msg (String): 28 or 14 bytes hexadecimal message string
Returns:
int: checksum in integer
"""
if len(msg) == 28:
offset = 0
elif len(msg) == 14:
offset = 112-56
else:
raise RuntimeError("wrong message length, need to be 28 or 14 bytes")
msgbin = util.hex2bin(msg)
crc = 0
for i in xrange(len(msgbin)):
if int(msgbin[i]):
crc ^= util.MODES_CHECKSUM_TABLE[i+offset]
return crc
from . import util
from .util import crc
def df(msg):
@@ -71,7 +49,7 @@ def icao(msg):
# raise RuntimeError("Message DF must be in (4, 5, 20, 21)")
return None
c0 = crc(msg)
c0 = util.bin2int(crc(msg, encode=True))
c1 = util.hex2int(msg[-6:])
icao = '%06X' % (c0 ^ c1)
return icao

View File

@@ -19,36 +19,8 @@ along with this program. If not, see <http://www.gnu.org/licenses/>.
import math
MODES_CHECKSUM_TABLE = [
0x3935ea, 0x1c9af5, 0xf1b77e, 0x78dbbf,
0xc397db, 0x9e31e9, 0xb0e2f0, 0x587178,
0x2c38bc, 0x161c5e, 0x0b0e2f, 0xfa7d13,
0x82c48d, 0xbe9842, 0x5f4c21, 0xd05c14,
0x682e0a, 0x341705, 0xe5f186, 0x72f8c3,
0xc68665, 0x9cb936, 0x4e5c9b, 0xd8d449,
0x939020, 0x49c810, 0x24e408, 0x127204,
0x093902, 0x049c81, 0xfdb444, 0x7eda22,
0x3f6d11, 0xe04c8c, 0x702646, 0x381323,
0xe3f395, 0x8e03ce, 0x4701e7, 0xdc7af7,
0x91c77f, 0xb719bb, 0xa476d9, 0xadc168,
0x56e0b4, 0x2b705a, 0x15b82d, 0xf52612,
0x7a9309, 0xc2b380, 0x6159c0, 0x30ace0,
0x185670, 0x0c2b38, 0x06159c, 0x030ace,
0x018567, 0xff38b7, 0x80665f, 0xbfc92b,
0xa01e91, 0xaff54c, 0x57faa6, 0x2bfd53,
0xea04ad, 0x8af852, 0x457c29, 0xdd4410,
0x6ea208, 0x375104, 0x1ba882, 0x0dd441,
0xf91024, 0x7c8812, 0x3e4409, 0xe0d800,
0x706c00, 0x383600, 0x1c1b00, 0x0e0d80,
0x0706c0, 0x038360, 0x01c1b0, 0x00e0d8,
0x00706c, 0x003836, 0x001c1b, 0xfff409,
0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000,
0x000000, 0x000000, 0x000000, 0x000000
]
# the polynominal generattor code for CRC
GENERATOR = "1111111111111010000001001"
def hex2bin(hexstr):
@@ -70,4 +42,40 @@ def hex2int(hexstr):
def df(msg):
"""Decode Downlink Format vaule, bits 1 to 5."""
msgbin = hex2bin(msg)
return bin2int(msgbin[0: 5])
return bin2int(msgbin[0:5])
def crc(msg, encode=False):
"""Mode-S Cyclic Redundancy Check
Detect if bit error occurs in the Mode-S message
Args:
msg (string): 28 bytes hexadecimal message string
encode (bool): True to encode the date only and return the checksum
Returns:
string: message checksum, or partity bits (encoder)
"""
msgbin = list(hex2bin(msg))
if encode:
msgbin[-24:] = ['0'] * 24
# loop all bits, except last 24 piraty bits
for i in range(len(msgbin)-24):
# if 1, perform modulo 2 multiplication,
if msgbin[i] == '1':
for j in range(len(GENERATOR)):
# modulo 2 multiplication = XOR
msgbin[i+j] = str((int(msgbin[i+j]) ^ int(GENERATOR[j])))
# last 24 bits
reminder = ''.join(msgbin[-24:])
return reminder
def floor(x):
""" Mode-S floor function
Defined as the greatest integer value k, such that k <= x
eg.: floor(3.6) = 3, while floor(-3.6) = -4
"""
return int(math.floor(x))

View File

@@ -23,7 +23,7 @@ setup(
# Versions should comply with PEP440. For a discussion on single-sourcing
# the version across setup.py and the project code, see
# https://packaging.python.org/en/latest/single_source_version.html
version='1.0.2',
version='1.0.5',
description='Python Mode-S Decoder',
long_description=long_description,
@@ -58,10 +58,10 @@ setup(
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
# 'Programming Language :: Python :: 3',
# 'Programming Language :: Python :: 3.3',
# 'Programming Language :: Python :: 3.4',
# 'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
# What does your project relate to?

View File

@@ -7,6 +7,22 @@ sys.path.insert(0, parentdir)
import pyModeS as pms
from pyModeS import adsb
from pyModeS import ehs
from pyModeS import util
# === TEST common functions ===
def test_hex2bin():
assert util.hex2bin('6E406B') == "011011100100000001101011"
def test_crc():
# crc decoder
checksum = util.crc("8D406B902015A678D4D220AA4BDA")
assert checksum == "000000000000000000000000"
# crc encoder
parity = util.crc("8D406B902015A678D4D220AA4BDA", encode=True)
assert util.hex2bin("AA4BDA") == parity
# === TEST ADS-B package ===
@@ -23,13 +39,28 @@ def test_adsb_callsign():
assert adsb.callsign("8D406B902015A678D4D220AA4BDA") == "EZY85MH_"
def test_adsb_position():
pos = adsb.position("8D40058B58C901375147EFD09357",
"8D40058B58C904A87F402D3B8C59",
1446332400, 1446332405)
def test_adsb_airborne_position():
pos = adsb.airborne_position("8D40058B58C901375147EFD09357",
"8D40058B58C904A87F402D3B8C59",
1446332400, 1446332405)
assert pos == (49.81755, 6.08442)
def test_adsb_airborne_position_with_ref():
pos = adsb.airborne_position_with_ref("8D40058B58C901375147EFD09357",
49.0, 6.0)
assert pos == (49.82410, 6.06785)
pos = adsb.airborne_position_with_ref("8D40058B58C904A87F402D3B8C59",
49.0, 6.0)
assert pos == (49.81755, 6.08442)
def test_adsb_surface_position_with_ref():
pos = adsb.surface_position_with_ref("8FC8200A3AB8F5F893096B22B4A8",
-43.5, 172.5)
assert pos == (-43.48564, 175.87195)
def test_adsb_alt():
assert adsb.altitude("8D40058B58C901375147EFD09357") == 39000
@@ -37,8 +68,8 @@ def test_adsb_alt():
def test_adsb_velocity():
vgs = adsb.velocity("8D485020994409940838175B284F")
vas = adsb.velocity("8DA05F219B06B6AF189400CBC33F")
assert vgs == (159, 182.9, -263, 'GS')
assert vas == (376, 244.0, -274, 'AS')
assert vgs == (159, 182.9, -14, 'GS')
assert vas == (376, 244.0, -37, 'AS')
def test_nic():
@@ -102,7 +133,7 @@ def test_ehs_BDS60_functions():
# === Decode sample data file ===
def adsb_decode_all(n=None):
print "===== Decode all ADS-B sample data====="
print("===== Decode all ADS-B sample data=====")
import csv
f = open('adsb.csv', 'rt')
@@ -118,9 +149,9 @@ def adsb_decode_all(n=None):
icao = adsb.icao(m)
tc = adsb.typecode(m)
if 1 <= tc <= 4:
print ts, m, icao, tc, adsb.category(m), adsb.callsign(m)
print(ts, m, icao, tc, adsb.category(m), adsb.callsign(m))
if tc == 19:
print ts, m, icao, tc, adsb.velocity(m)
print(ts, m, icao, tc, adsb.velocity(m))
if 5 <= tc <= 18:
if adsb.oe_flag(m):
msg1 = m
@@ -132,11 +163,11 @@ def adsb_decode_all(n=None):
if msg0 and msg1:
pos = adsb.position(msg0, msg1, t0, t1)
alt = adsb.altitude(m)
print ts, m, icao, tc, pos, alt
print(ts, m, icao, tc, pos, alt)
def ehs_decode_all(n=None):
print "===== Decode all Mode-S EHS sample data====="
print("===== Decode all Mode-S EHS sample data=====")
import csv
f = open('ehs.csv', 'rt')
for i, r in enumerate(csv.reader(f)):
@@ -150,21 +181,21 @@ def ehs_decode_all(n=None):
if vBDS:
if vBDS == "BDS20":
print ts, m, icao, vBDS, ehs.callsign(m)
print(ts, m, icao, vBDS, ehs.callsign(m))
if vBDS == "BDS40":
print ts, m, icao, vBDS, ehs.alt_mcp(m), \
ehs.alt_fms(m), ehs.pbaro(m)
print(ts, m, icao, vBDS, ehs.alt_mcp(m), \
ehs.alt_fms(m), ehs.pbaro(m))
if vBDS == "BDS50":
print ts, m, icao, vBDS, ehs.roll(m), ehs.track(m), \
ehs.gs(m), ehs.rtrack(m), ehs.tas(m)
print(ts, m, icao, vBDS, ehs.roll(m), ehs.track(m), \
ehs.gs(m), ehs.rtrack(m), ehs.tas(m))
if vBDS == "BDS60":
print ts, m, icao, vBDS, ehs.heading(m), ehs.ias(m), \
ehs.mach(m), ehs.baro_vr(m), ehs.ins_vr(m)
print(ts, m, icao, vBDS, ehs.heading(m), ehs.ias(m), \
ehs.mach(m), ehs.baro_vr(m), ehs.ins_vr(m))
else:
print ts, m, icao, vBDS
print(ts, m, icao, vBDS)
if __name__ == '__main__':
adsb_decode_all(100)