Compare commits

...

No commits in common. "gps" and "gh-pages" have entirely different histories.

48 changed files with 563 additions and 9669 deletions

2
.gitattributes vendored
View File

@ -1,2 +0,0 @@
# Auto detect text files and perform LF normalization
* text=auto

100
.gitignore vendored
View File

@ -1,100 +0,0 @@
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
.hypothesis/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# IPython Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# dotenv
.env
# virtualenv
venv/
ENV/
# Spyder project settings
.spyderproject
# Rope project settings
.ropeproject
.DS_Store
hblink.cfg
*.config
*.bak
rules.py
subscriber_ids.*
local_subscriber_ids.*
peer_ids.*
local_peer_ids.*
talkgroup_ids.*

1
CNAME Normal file
View File

@ -0,0 +1 @@
hblink3.hbl.ink

Binary file not shown.

Before

Width:  |  Height:  |  Size: 42 KiB

View File

@ -1,245 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
inkscape:version="1.0beta1 (d565813, 2019-09-28)"
sodipodi:docname="HBlink.svg"
id="svg877"
height="411.17413"
width="1042.9242"
viewBox="49.656 217.125 1042.9242 411.17414"
version="1.1">
<sodipodi:namedview
inkscape:current-layer="svg877"
inkscape:window-maximized="0"
inkscape:window-y="23"
inkscape:window-x="583"
inkscape:cy="48.366866"
inkscape:cx="574.39926"
inkscape:zoom="1"
fit-margin-left="5"
fit-margin-bottom="5"
fit-margin-right="5"
fit-margin-top="5"
units="px"
inkscape:pagecheckerboard="true"
showgrid="false"
id="namedview879"
inkscape:window-height="1348"
inkscape:window-width="1943"
inkscape:pageshadow="2"
inkscape:pageopacity="0"
guidetolerance="10"
gridtolerance="10"
objecttolerance="10"
borderopacity="1"
inkscape:document-rotation="0"
bordercolor="#666666"
pagecolor="#ffffff" />
<defs
id="defs837">
<font-face
overline-thickness="0"
overline-position="0"
strikethrough-thickness="0"
strikethrough-position="0"
v-hanging="0"
v-mathematical="0"
v-alphabetic="0"
v-ideographic="0"
hanging="0"
mathematical="0"
alphabetic="0"
ideographic="0"
accent-height="0"
stemh="0"
stemv="0"
id="font-face833"
font-weight="400"
descent="-255.00488"
ascent="945.0073"
cap-height="669"
x-height="669"
slope="0"
underline-thickness="20"
underline-position="-133"
units-per-em="1000"
panose-1="2 0 6 0 0 0 0 0 0 0"
font-size="96"
font-family="Ethnocentric">
<font-face-src>
<font-face-name
name="EthnocentricRg-Regular" />
</font-face-src>
</font-face>
<font-face
overline-thickness="0"
overline-position="0"
strikethrough-thickness="0"
strikethrough-position="0"
v-hanging="0"
v-mathematical="0"
v-alphabetic="0"
v-ideographic="0"
hanging="0"
mathematical="0"
alphabetic="0"
ideographic="0"
accent-height="0"
stemh="0"
stemv="0"
id="font-face835"
font-weight="400"
descent="-255.00488"
ascent="945.0073"
cap-height="669"
x-height="669"
slope="0"
underline-thickness="20"
underline-position="-133"
units-per-em="1000"
panose-1="2 0 6 0 0 0 0 0 0 0"
font-size="48"
font-family="Ethnocentric">
<font-face-src>
<font-face-name
name="EthnocentricRg-Regular" />
</font-face-src>
</font-face>
</defs>
<metadata
id="metadata839"> Produced by OmniGraffle 7.12.1
<dc:date>2018-03-14 13:37:44 +0000</dc:date>
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<g
transform="matrix(3.5262508,0,0,3.5262508,-159.40153,-655.56235)"
stroke-opacity="1"
stroke="none"
stroke-dasharray="none"
fill-opacity="1"
fill="none"
id="Canvas_2">
<title
id="title841">Canvas 2</title>
<g
id="Canvas_2: Layer 1">
<title
id="title843">Layer 1</title>
<g
id="Group_40">
<g
id="Graphic_39">
<title
id="title845">path6007</title>
<path
inkscape:connector-curvature="0"
id="path847"
stroke-width="3"
stroke-linejoin="round"
stroke-linecap="round"
stroke="#009051"
d="m 72.52062,328.5 h 225.5218 c 6.17355,0 11.1782,5.00465 11.1782,11.1782 v 0 c 0,6.17355 -5.00465,11.1782 -11.1782,11.1782 H 72.52062 c -6.17355,0 -11.1782,-5.00465 -11.1782,-11.1782 v 0 c 0,-6.17355 5.00465,-11.1782 11.1782,-11.1782 z" />
</g>
<g
id="Graphic_38">
<g
style="fill:#009051"
id="text852"
transform="translate(54.656,222.125)"
aria-label="HB">
<path
inkscape:connector-curvature="0"
id="path881"
style="font-weight:400;font-size:96px;font-family:Ethnocentric;fill:#009051"
d="M 84,91 H 64.224 V 66.232 H 26.016 V 91 H 6.048 V 26.776 H 26.016 V 49.528 H 64.224 V 26.776 H 84 Z" />
<path
inkscape:connector-curvature="0"
id="path883"
style="font-weight:400;font-size:96px;font-family:Ethnocentric;fill:#009051"
d="m 168.7155,57.976 q 4.224,1.248 7.104,4.896 2.976,3.648 2.976,9.408 0,4.032 -1.248,7.488 -1.248,3.36 -4.224,5.856 -2.976,2.496 -8.064,3.936 -4.992,1.44 -12.576,1.44 H 96.2355 V 51.928 h 56.832 q 2.208,0 3.84,-0.864 1.728,-0.96 1.728,-3.456 0,-2.4 -1.728,-3.264 -1.728,-0.864 -3.84,-0.864 h -56.832 l 13.44,-16.704 h 42.528 q 5.76,0 10.368,1.152 4.704,1.056 7.968,3.36 3.36,2.208 5.088,5.568 1.824,3.264 1.824,7.68 0,2.88 -0.768,5.088 -0.768,2.208 -2.016,3.936 -1.152,1.632 -2.784,2.784 -1.536,1.056 -3.168,1.632 z m -52.512,7.68 v 8.832 h 36.576 q 3.264,0 4.704,-1.152 1.44,-1.152 1.44,-3.36 0,-2.112 -1.44,-3.168 -1.44,-1.152 -4.704,-1.152 z" />
</g>
</g>
<g
id="Graphic_37">
<g
style="fill:#ff9300"
id="text857"
transform="translate(209.109,275)"
aria-label="link">
<path
inkscape:connector-curvature="0"
id="path886"
style="font-weight:400;font-size:48px;font-family:Ethnocentric;fill:#ff9300"
d="M 3.024,45 Z M 37.824,36.744 31.392,45 H 3.024 V 12.888 h 9.936 v 23.856 z" />
<path
inkscape:connector-curvature="0"
id="path888"
style="font-weight:400;font-size:48px;font-family:Ethnocentric;fill:#ff9300"
d="m 41.32425,45 z m 9.936,0 h -9.936 V 12.888 h 9.936 z" />
<path
inkscape:connector-curvature="0"
id="path890"
style="font-weight:400;font-size:48px;font-family:Ethnocentric;fill:#ff9300"
d="m 57.34875,45 z m 32.688,0.528 q -0.96,0 -1.92,-0.336 -0.912,-0.288 -2.064,-1.392 l -19.68,-17.664 V 45 h -9.024 V 18.36 q 0,-1.584 0.432,-2.736 0.48,-1.152 1.2,-1.872 0.768,-0.72 1.728,-1.056 1.008,-0.336 2.064,-0.336 0.912,0 1.824,0.336 0.96,0.288 2.16,1.392 l 19.68,17.664 V 12.888 h 9.072 V 39.48 q 0,1.584 -0.48,2.736 -0.432,1.152 -1.2,1.92 -0.72,0.72 -1.728,1.056 -1.008,0.336 -2.064,0.336 z" />
<path
inkscape:connector-curvature="0"
id="path892"
style="font-weight:400;font-size:48px;font-family:Ethnocentric;fill:#ff9300"
d="m 101.36775,45 z m 40.512,0 h -15.024 l -9.696,-8.448 q -2.496,-2.16 -3.84,-3.36 -1.296,-1.2 -2.112,-2.016 0.048,1.104 0.096,2.304 0.048,1.152 0.048,2.304 V 45 h -9.984 V 12.888 h 9.984 v 7.44 q 0,1.488 -0.048,2.928 -0.048,1.44 -0.144,2.688 0.96,-0.864 2.304,-2.112 1.392,-1.296 3.6,-3.12 l 9.264,-7.824 h 14.4 l -12.288,9.216 q -1.584,1.2 -2.832,2.112 -1.2,0.912 -2.16,1.584 -0.96,0.672 -1.776,1.2 -0.768,0.528 -1.536,1.008 1.392,0.96 3.36,2.4 1.968,1.44 5.088,3.984 z" />
</g>
</g>
<g
id="Graphic_36">
<path
inkscape:connector-curvature="0"
d="m 302.0625,336.9375 h 14.5771 v 6.1875 h -14.5771 z"
style="fill:#ffffff"
id="rect860" />
</g>
<g
id="Graphic_35">
<title
id="title863">path6381</title>
<path
inkscape:connector-curvature="0"
id="path865"
stroke-width="3"
stroke-linejoin="round"
stroke-linecap="round"
stroke="#ff9300"
d="M 116.9282,340.3125 H 342.45 c 6.17355,0 11.1782,5.00465 11.1782,11.1782 v 0 c 0,6.17355 -5.00465,11.1782 -11.1782,11.1782 H 116.9282 c -6.17355,0 -11.1782,-5.00465 -11.1782,-11.1782 v 0 c 0,-6.17355 5.00465,-11.1782 11.1782,-11.1782 z" />
</g>
<g
id="Graphic_34">
<path
inkscape:connector-curvature="0"
d="m 99,347.625 h 14.5771 v 6.1875 H 99 Z"
style="fill:#ffffff"
id="rect868" />
</g>
<g
id="Line_33">
<path
inkscape:connector-curvature="0"
d="M 93.9375,350.85641 H 120.375"
style="stroke:#009051;stroke-width:3;stroke-linecap:round;stroke-linejoin:round"
id="line871" />
</g>
</g>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 9.1 KiB

View File

@ -1,241 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 2007 Free Software Foundation, Inc. <http://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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 <http://www.gnu.org/licenses/>.
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 <http://www.gnu.org/philosophy/why-not-lgpl.html>.

241
README.md Executable file → Normal file
View File

@ -1,240 +1 @@
### This project has morphed into HBNet. It is still under heavy development and not ready for production. You can see it [here](https://github.com/kf7eel/hblink3/tree/hbnet). The example/development server can be found at [https://demo.hbnet.xyz](https://demo.hbnet.xyz).
# GPS/Data Application
This repository contains everything needed to decode DMR GPS packets and SMS for HBLink3. This application can act as a master or peer and receive data as a group call or private call. It is designed to work in a multi system/user network.
Files modified from original master branch of HBLink3:
* bridge.py
* config.py
#### Required modules
* pynmea2
* aprslib
* maidenhead
#### Optional Modules
* Flask - Required for dashboard
* smtplib - Required for sending email. If pip fails to install module, it may already be installed as most Linux distributions have this module by default.
* traceback - If pip fails to install module, it may already be installed as most Linux distrobutions have this module by default.
* slixmpp - Required for upcoming XMPP gateway.
* folium - Required for mapping on dashboard.
This should work for DMR radios that send location data as a UTF-8 NMEA sentence. I am hopping to add support for more radios in the future.
### Differences in branches
* **GPS**: Contains the GPS/Data Application.
* **aprs_features**: Contains the GPS/Data Application and a modified version of the APRS implementation for repeaters and hotspots by **IU7IGU**. (See [https://github.com/iu7igu/hblink3-aprs](https://github.com/iu7igu/hblink3-aprs) for his work). I combined these for convenience.
## Confirmed working:
Actually tested
| Radio | GPS | SMS |
|-------|:---:|:---:|
| Anytone D878| YES | YES |
| Anytone D578| YES | YES |
| BTech DMR-6x2 | YES | Most likely |
| MD-380 (MD380tools, no GPS) | - | YES |
| MD-380 (stock firmware, GPS) | YES | Most likely |
| MD-390 (stock firmware) | YES | YES |
| Retevis RT73* | YES | YES |
| Ailunce HD1 | YES | YES |
*RT73 must have unconfirmed data setting enabled.
## Highly suspected to work:
Not tested yet, but will most likely work.
| Radio | GPS | SMS |
|-------|:---:|:---:|
| Anytone D868 | Most likely | Most likely |
| TYT MD-2017 | Most likely | Likely |
| TYT MD-9600 | Most likely | Likely |
| Retevis RT8 | Most likely | Likely |
## Tested, but with issues.
Tested, but with bugs present.
| Radio | GPS | SMS |
|-------|:---:|:---:|
| Alinco DJ-MD5TGP | WIP | Most likely |
| Motorola DP3601| WIP | WIP |
## Would like to test:
Connect Systems GPS enabled radios
## Features
* Decode GPS locations and upload APRS position packets
* Each user/DMR ID can customize APRS position
* Ability to receive data as a private call or group call
* Trigger a command or script via DMR SMS
* Optional web dashboard to show APRS packets uploaded
* Display bulletins sent via SMS on web dashboard
## How it works
A user should configure their radio for the DMR ID of the application and private or group call. When a position is received by the application, it will extract the coordinates and create an APRS position packet. The application will find the callsign of the user based on the sending radio's DMR ID. It is essential to have an up to date subscriber_ids file for this to work. A predefined APRS SSID is appended to the callsign. The APRS location packet is then uploaded to APRS-IS. No setup is required beforehand on the part of the user. This is pretty much "plug and play."
For example, N0CALL has a DMR ID of 1234567. N0CALL's radio sends a position to the application. The application will query the subscriber_ids file for DMR ID 1234567. The result will be N0CALL. An APRS location pack is created and uploaded to APRS-IS.
## Individual user/DMR ID APRS settings
By default, all APRS positions will have an SSID of 15, a default comment, and the callsign of the DMR user. These default settings can be changed.
The comment, SSID, and icon can be set for each individual user/DMR ID the application sees. The application stores all the setting in a file. You may have different SSIDs, icons, and comments for different DMR IDs. This is done via DMR SMS using the following commands:
| Command | Description | Example |
|-------|:---:|:---:|
|**@SSID**|Change SSID of user callsign.|`@SSID 7`|
|**@ICON**|Change the icon of the APRS position. *See [http://aprs.net/vm/DOS/SYMBOLS.HTM](http://aprs.net/vm/DOS/SYMBOLS.HTM) for icon list.|`@icon /p`|
|**@COM**|Change the comment of the APRS.|`@COM This is a test comment.`|
|**@MH**|Set you location by maidenhead grid square. Designed for radios with no GPS or that are not compatable yet.|`@MH DN97uk`|
|**@BB**|Post a bulliten to the web dashboard.|`@BB This is a test bulletin.`|
|**@[CALLSIGN W/ SSID] A-[MESSAGE]**|Send a message to another station via APRS.|`@N0CALL-15 A-This is a test.`|
|**[EMAIL ADDRESS] E-[MESSAGE]**|Send an email to an email address.|`test@example.org E-This is a test.`|
Send a DMR SMS to the configured dmr_data_id in the application with the desired command followed by the value. For example, to change your icon to a dog, the command would be `@ICON /p` (see the icon table for values). Changing your SSID is as simple as `@SSID 7`, and `@COM Testing 123` will change the comment.
Sending `@BB Test` will result in a post to the bulletin board with the messaage of "Test".
**To remove any of the stored values, just send the appropriate command without any input.** `@COM` will remove the stored comment, `@ICON` will remove the stored icon, and `@COM` will remove the strored comment. Any position now reports sent will have the default settings.
## Web Dashboard
The web dashboard is completely optional. Python module flask is required for this to work. The web dashboard will display the last 15 positions of radios sent to APRS-IS. The dashboard will also sh user bulletin. A bulletin is a message sent via SMS that will display on the web dashboard. There are several uses for this, including: testing SMS functionality of radio, announcements, and moire. It is a novel feature. The page will automatically reload every 2 minutes. Setup is rather simple. Just modify the example config in the dashboard directory and rename it to dashboard_settings.py. Then start dashboard.py.
## APRS messaging
**At this time, only sending of messages from DMR SMS to APRS-IS is supported.** I find this feature very pointless because it will only go one way, but someone else may find it important. **Messages from sent from APRS-IS to DMR SMS will not work.** I have not written the code for this yet. It will likley be a long time before this is a possibility.
## APRS TOCALL
The project was granted a [tocall](http://www.aprs.org/aprs11/tocalls.txt) of **APHBLx** by Bob Bruniga, WB4APR. This will identify that your APRS position came from HBLink. The x on the end can be any letter/number. Here are the current designations of APHBLx:
* **APHBL3** - HBlink3 D-APRS gateway
* **APHBLD** - DMRlink D-APRS gateway (the IPSC version of the project)
* **_APHBLS_** - Planned, but not in use: HBLink3 via KISS TNC
## Configuration
See hblink_SAMPLE.cfg, rules_SAMPLE.py, and gps_data_SAMPLE.cfg for examples.
## Special thanks to:
**N0MJS** - For creating HBLink and dmr_utils. This project not possible without him.
**IU7IGU** - For creating APRS position beaconing for PEER connections.
**IV3JDV** - For helping debug SMS in Anytone radios.
**KD7LMN** - For pointing out a critical bug.
**KB5PBM** - For helping implement support for MD-380 type radios.
**EI7IG** - For writing the page explaining MD-380 type GPS packets.
**M0GLJ** - For assisting with Motorola testing.
## Resources for DMR data
I spent many hours looking at the following for this project. You may find these links useful.
https://github.com/travisgoodspeed/md380tools/issues/160
https://jpronans.github.io/ei7ig/dmr.html
http://cloud.dstar.su/files/G4KLX/MMDVM/MMDVM%20Specification%2020150922.pdf
https://wiki.brandmeister.network/index.php/NMEA_Location_Reporting
https://forums.radioreference.com/threads/motorola-lrrp-protocol.370081/
https://forums.radioreference.com/threads/lrrp-decoding.359575/
https://github.com/polkabana/go-dmr
https://github.com/nonoo/dmrshark
https://wiki.brandmeister.network/index.php/Compressed_Location_Reporting
All of the ETSI DMR documents (ETSI 102 361-1 through 361-4).
The Shark RF forums.
---
### FOR SUPPORT, DISCUSSION, GETTING INVOLVED ###
Please join the DVSwitch group at groups.io for online forum support, discussion, and to become part of the development team.
DVSwitch@groups.io
A voluntary registrty for HBlink systems with public access has been created at http://hblink-register.com.es Please consider listing your system if you allow open access.
---
## PROJECT: Open Source HomeBrew Repeater Proctol Client/Master. ##
**UPDATES:**
**PURPOSE:** Thanks to the work of Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT we have an open protocol for internetworking DMR repeaters. Unfortunately, there's no generic client and/or master stacks. This project is to build an open-source, python-based implementation. You are free to use this software however you want, however we ask that you provide attribution in some public venue (such as project, club, organization web site). This helps us see where the software is in use and track how it is used.
For those who will ask: This is a piece of software that implements an open-source, amateur radio networking protocol. It is not a network. It is not intended to be a network. It is not intended to replace or circumvent a network. People do those things, code doesn't.
**PROPERTY:**
This work represents the author's interpretation of the HomeBrew Repeater Protocol, based on the 2015-07-26 documents from DMRplus, "IPSC Protocol Specs for homebrew DMR repeater" as written by Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT, also licenced under Creative Commons BY-NC-SA license.
**WARRANTY**
None. The owners of this work make absolutely no warranty, express or implied. Use this software at your own risk.
**PRE-REQUISITE KNOWLEDGE:**
This document assumes the reader is familiar with Linux/UNIX, the Python programming language and DMR.
**Using docker version**
To work with provided docker setup you will need:
* A private repository with your configuration files (all .cfg files in repo will be copyed to the application root directory on start up)
* A service user able to read your private repository (or be brave and publish your configuration, or be really brave and give your username and password to the docker)
* A server with docker installed
* Follow this simple steps:
Build your own image from source
```bash
docker build . -t millaguie/hblink:3.0.0
```
Or user a prebuilt one in docker hub: millaguie/hblink:3.0.0
Wake up your container
```bash
touch /var/log/hblink.log
chown 65000 /var/log/hblink.log
run -v /var/log/hblink.log:/var/log/hblink.log -e GIT_USER=$USER -e GIT_PASSWORD=$PASSWORD -e GIT_REPO=$URL_TO_REPO_WITHOUT_HTTPS:// -p 54000:54000 millaguie/hblink:3.0.0
```
**MORE DOCUMENTATION TO COME**
***0x49 DE N0MJS***
Copyright (C) 2016-2020 Cortney T. Buffington, N0MJS n0mjs@me.com
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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
This branch is just the [website](https://kf7eel.github.io/hblink3/).

1
_config.yml Normal file
View File

@ -0,0 +1 @@
theme: jekyll-theme-slate

156
api_doc.md Normal file
View File

@ -0,0 +1,156 @@
# API Documentation
## [Home](https://kf7eel.github.io/hblink3/) | [Configuration](/hblink3/config_doc.html) | [API Documentation](https://kf7eel.github.io/hblink3/api_doc.html) | [HBlink Website](https://hblink-org.github.io/)
----
The API is a new feature that allows users to interact with external applications via SMS and send messages users on other HBLink servers. The API is built into the D-APRS dashboard. All interaction takes place over HTTP POST requests in JSON format. This allows a single application to be used by multiple servers. Applications can be delevopen in multiple langauges.
There are presently 3 modes for data exchange, "**msg_xfer**", "**app**", and "**raw**".
### app
**app** mode is used specify the request as an app request. An app request contains a one time token generated by the sending HBLink server allowing the external application to send a one time response, without having to have login credentials on the sending server. The auth_token can only be used once.
Example of app request, initiated by a user on an HBLink server via SMS:
`{
"mode": "app",
"system_shortcut": "ABC",
"server_name": "Test HBlink Network",
"response_url": "http://localhost:8093/api/",
"auth_token": "1234567899",
"data": {
"source_id": 1234,
"slot": 2,
"msg_type": "unit",
"msg_format": "motorola",
"message": "TIME"
}
}`
mode: Set to "app" as this is an app request.
system_shortcut: This is set in the sending server's config.
server_name: This is the name of the sending server.
Response_url: This is the URL where we should send a response. We can initiate a POST to this URL for a response. This is the URL of the sending server's D-APRS dashboard.
auth_token: This is the auth_token of the sending server. Our response must contain this. See example below.
source_id : The source radio DMR ID.
slot: Timeslot the message was received on.
msg_type: Type of call received. This should be group or unit.
msg_format: Format of the received SMS. A value of motorola is the only option at this time.
message: The actual text of the SMS.
Below is an example of a response that can be sent back to the sending HBLink server. The response is sent as a POST to the response:
`{
"mode": "app",
"app_name": "Test HBlink App",
"app_shortcut": "APP",
"auth_token": "1234567899",
"data": {
"1": {
"destination_id": 3153591,
"slot": 0,
"msg_type": "unit",
"msg_format": "motorola",
"message": "The time is 21:25."
},
"2": {
"destination_id": 3153591,
"slot": 0,
"msg_type": "unit",
"msg_format": "motorola",
"message": "The date is April 26th, 2021."
}
}
}`
mode: Set to "app" as this is an app response.
app_shortcut: This is the system shortcut of the external application.
app_name: This is the name of the responding application.
auth_token: This is the auth_token that was originally sent.
destination_id: DMR ID of destination radio.
slot: Timeslot to send message on. A value of 0 will allow the receiving server to determine which timeslot to send the generated SMS on. This should be 0 most of the time. Other values are 1 or 2, for timeslots.
msg_format: Format to generate SMS in. A value of motorola is the only option at this time.
message: The actual text of the SMS.
Multiple SMS can be generated from a single response, useful for sending multiple SMS as a response.
### msg_xfer
**msg_xfer** is used to send a message. When the D-APRS dashboard receives a msg_xfer request, it generates an SMS message and places it in HBLink's SMS sending que.
With msg_xfer, there are 2 authentication types, "public" and "private". With private authentication, the requesting server (or application) must provide a username and password, specified in _authorized_users_ of the receiving server's rules.py. Public authentication is still a work in progress. Public authentication will allow one server to send to another server without having a shared username or password.
Here is an example of a msg_xfer JSON POST using private authentication:
`{
"mode": "msg_xfer",
"system_shortcut": "ABC",
"server_name": "Test HBlink Network",
"response_url": "http://localhost:8093/api/",
"auth_type": "private",
"credentials": {
"user": "test_name",
"password": "passw0rd"
},
"data": {
"1": {
"source_id": 1234,
"destination_id": 3153591,
"slot": 0,
"msg_type": "unit",
"msg_format": "motorola",
"message": "text of the message"
},
"2": {
"source_id": 1234,
"destination_id": 3153591,
"slot": 0,
"msg_type": "unit",
"msg_format": "motorola",
"message": "text of the 2nd message"
}
}
}`
system_shortcut: This is set in the sending server's config. This value is used to find a username and password on the receiving server's side for authentication. This is also the shortcut that users specify in their SMS.
server_name: This is the name of the sending server.
Response_url: This is the URL where we should send a response. This is important for public authentication. It is the location of the sending servers D-APRS dashboard.
auth_type: pubic or private. If private, then "credentials" will be appended with the username and password.
data: The dashboard forms an SMS based on the values in this field.
Multiple SMS can be generated from a single request, useful for sending an SMS to multiple recipients or multiple messages to the same recipient.
source_id and destination_id: The source and destination DMR ID.
slot: Timeslot to send message on. A value of 0 will allow the receiving server to determine which timeslot to send the generated SMS on. This should be 0 most of the time. Other values are 1 or 2, for timeslots.
msg_type: This should be group or unit. Unit for a private call, group for a group call.
msg_format: Format to generate SMS in. A value of motorola is the only option at this time.
message: The actual text of the SMS.
## raw
This is still a work in progress.

1210
bridge.py

File diff suppressed because it is too large Load Diff

View File

@ -1,295 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
This is a very simple call/packet router for Homebrew Repeater Protocol. It
will forward traffic from any system to all other systems configured in the
hblink.py configuration file. It does not check for call contentions or
filter TS/TGID combinations. It should really only be used as a proxy to
hide multiple Homebrew repater protocol systems behind what appears as a single
repeater, hotspot, etc.
As is, this program only works with group voice packets. It could work for all
of them by removing a few things.
IT ONLY WORKS FOR HBP SYSTEMS!!! Using it with OpenBridge or XLX wouldn't make
a lot of sense, and has the potential to do bad things.
'''
# Python modules we need
import sys
from bitarray import bitarray
from time import time
from importlib import import_module
from types import ModuleType
# Twisted is pretty important, so I keep it separate
from twisted.internet.protocol import Factory, Protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet import reactor, task
# Things we import from the main hblink module
from hblink import HBSYSTEM, OPENBRIDGE, systems, hblink_handler, reportFactory, REPORT_OPCODES, config_reports, mk_aliases, acl_check
from dmr_utils3.utils import bytes_3, int_id, get_alias
from dmr_utils3 import decode, bptc, const
import config
import log
import const
# The module needs logging logging, but handlers, etc. are controlled by the parent
import logging
logger = logging.getLogger(__name__)
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
__author__ = 'Cortney T. Buffington, N0MJS'
__copyright__ = 'Copyright (c) 2016-2018 Cortney T. Buffington, N0MJS and the K0USY Group'
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
__license__ = 'GNU GPLv3'
__maintainer__ = 'Cort Buffington, N0MJS'
__email__ = 'n0mjs@me.com'
__status__ = 'pre-alpha'
# Module gobal varaibles
class bridgeallSYSTEM(HBSYSTEM):
def __init__(self, _name, _config, _report):
HBSYSTEM.__init__(self, _name, _config, _report)
self._laststrid = ''
# Status information for the system, TS1 & TS2
# 1 & 2 are "timeslot"
self.STATUS = {
1: {
'RX_START': time(),
'RX_LOSS': 0,
'RX_SEQ': 0,
'RX_RFS': b'\x00',
'TX_RFS': b'\x00',
'RX_STREAM_ID': b'\x00',
'TX_STREAM_ID': b'\x00',
'RX_TGID': b'\x00\x00\x00',
'TX_TGID': b'\x00\x00\x00',
'RX_TIME': time(),
'TX_TIME': time(),
'RX_TYPE': const.HBPF_SLT_VTERM,
},
2: {
'RX_START': time(),
'RX:LOSS': 0,
'RX_SEQ': 0,
'RX_RFS': b'\x00',
'TX_RFS': b'\x00',
'RX_STREAM_ID': b'\x00',
'TX_STREAM_ID': b'\x00',
'RX_TGID': b'\x00\x00\x00',
'TX_TGID': b'\x00\x00\x00',
'RX_TIME': time(),
'TX_TIME': time(),
'RX_TYPE': const.HBPF_SLT_VTERM,
}
}
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
pkt_time = time()
dmrpkt = _data[20:53]
_bits = _data[15]
if _call_type == 'group':
# Is this is a new call stream?
new_stream = (_stream_id != self.STATUS[_slot]['RX_STREAM_ID'])
if new_stream:
self.STATUS[_slot]['RX_START'] = pkt_time
self.STATUS[_slot]['RX_LOSS'] = 0
self.STATUS[_slot]['RX_SEQ'] = _seq
logger.info('(%s) *CALL START* STREAM ID: %s SUB: %s (%s) PEER: %s (%s) TGID %s (%s), TS %s', \
self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot)
else:
# This could be much better, it will have errors during roll-over
if _seq > (self.STATUS[_slot]['RX_SEQ'] + 1):
#print(_seq, self.STATUS[_slot]['RX_SEQ'])
self.STATUS[_slot]['RX_LOSS'] += _seq - (self.STATUS[_slot]['RX_SEQ'] + 1)
# Final actions - Is this a voice terminator?
if (_frame_type == const.HBPF_DATA_SYNC) and (_dtype_vseq == const.HBPF_SLT_VTERM) and (self.STATUS[_slot]['RX_TYPE'] != const.HBPF_SLT_VTERM):
call_duration = pkt_time - self.STATUS[_slot]['RX_START']
logger.info('(%s) *CALL END* STREAM ID: %s SUB: %s (%s) PEER: %s (%s) TGID %s (%s), TS %s, Loss: %s, Duration: %s', \
self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot, self.STATUS[_slot]['RX_LOSS'], call_duration)
for _target in self._CONFIG['SYSTEMS']:
if _target != self._system:
_target_status = systems[_target].STATUS
_target_system = self._CONFIG['SYSTEMS'][_target]
# BEGIN STANDARD CONTENTION HANDLING
#
# The rules for each of the 4 "ifs" below are listed here for readability. The Frame To Send is:
# From a different group than last RX from this HBSystem, but it has been less than Group Hangtime
# From a different group than last TX to this HBSystem, but it has been less than Group Hangtime
# From the same group as the last RX from this HBSystem, but from a different subscriber, and it has been less than stream timeout
# From the same group as the last TX to this HBSystem, but from a different subscriber, and it has been less than stream timeout
# The "continue" at the end of each means the next iteration of the for loop that tests for matching rules
#
if ((_dst_id != _target_status[_slot]['RX_TGID']) and ((pkt_time - _target_status[_slot]['RX_TIME']) < _target_system['GROUP_HANGTIME'])):
if _frame_type == const.HBPF_DATA_SYNC and _dtype_vseq == const.HBPF_SLT_VHEAD and self.STATUS[_slot]['RX_STREAM_ID'] != _stream_id:
logger.info('(%s) Call not routed to TGID %s, target active or in group hangtime: HBSystem: %s, TS: %s, TGID: %s', self._system, int_id(_dst_id), _target, _slot, int_id(_target_status[_slot]['RX_TGID']))
continue
if ((_dst_id != _target_status[_slot]['TX_TGID']) and ((pkt_time - _target_status[_slot]['TX_TIME']) < _target_system['GROUP_HANGTIME'])):
if _frame_type == const.HBPF_DATA_SYNC and _dtype_vseq == const.HBPF_SLT_VHEAD and self.STATUS[_slot]['RX_STREAM_ID'] != _stream_id:
logger.info('(%s) Call not routed to TGID%s, target in group hangtime: HBSystem: %s, TS: %s, TGID: %s', self._system, int_id(_dst_id), _target, _slot, int_id(_target_status[_slot]['TX_TGID']))
continue
if (_dst_id == _target_status[_slot]['RX_TGID']) and ((pkt_time - _target_status[_slot]['RX_TIME']) < const.STREAM_TO):
if _frame_type == const.HBPF_DATA_SYNC and _dtype_vseq == const.HBPF_SLT_VHEAD and self.STATUS[_slot]['RX_STREAM_ID'] != _stream_id:
logger.info('(%s) Call not routed to TGID%s, matching call already active on target: HBSystem: %s, TS: %s, TGID: %s', self._system, int_id(_dst_id), _target, _slot, int_id(_target_status[_slot]['RX_TGID']))
continue
if (_dst_id == _target_status[_slot]['TX_TGID']) and (_rf_src != _target_status[_slot]['TX_RFS']) and ((pkt_time - _target_status[_slot]['TX_TIME']) < const.STREAM_TO):
if _frame_type == const.HBPF_DATA_SYNC and _dtype_vseq == const.HBPF_SLT_VHEAD and self.STATUS[_slot]['RX_STREAM_ID'] != _stream_id:
logger.info('(%s) Call not routed for subscriber %s, call route in progress on target: HBSystem: %s, TS: %s, TGID: %s, SUB: %s', self._system, int_id(_rf_src), _target, _slot, int_id(_target_status[_slot]['TX_TGID']), int_id(_target_status[_slot]['TX_RFS']))
continue
# ACL Processing
if self._CONFIG['GLOBAL']['USE_ACL']:
if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']):
if _stream_id != _target_status[_slot]['TX_STREAM_ID']:
logger.info('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', _target, int_id(_stream_id), int_id(_rf_src))
_target_status[_slot]['TX_STREAM_ID'] = _stream_id
continue
if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']):
if _stream_id != _target_status[_slot]['TX_STREAM_ID']:
logger.info('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', _target, int_id(_stream_id), int_id(_dst_id))
_target_status[_slot]['TX_STREAM_ID'] = _stream_id
continue
if _slot == 2 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG2_ACL']):
if _stream_id != _target_status[_slot]['TX_STREAM_ID']:
logger.info('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s ON TGID %s BY GLOBAL TS2 ACL', _target, int_id(_stream_id), int_id(_dst_id))
_target_status[_slot]['TX_STREAM_ID'] = _stream_id
continue
if _target_system['USE_ACL']:
if not acl_check(_rf_src, _target_system['SUB_ACL']):
if _stream_id != _target_status[_slot]['TX_STREAM_ID']:
logger.info('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', _target, int_id(_stream_id), int_id(_rf_src))
_target_status[_slot]['TX_STREAM_ID'] = _stream_id
continue
if _slot == 1 and not acl_check(_dst_id, _target_system['TG1_ACL']):
if _stream_id != _target_status[_slot]['TX_STREAM_ID']:
logger.info('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s ON TGID %s BY SYSTEM TS1 ACL', _target, int_id(_stream_id), int_id(_dst_id))
_target_status[_slot]['TX_STREAM_ID'] = _stream_id
continue
if _slot == 2 and not acl_check(_dst_id, _target_system['TG2_ACL']):
if _stream_id != _target_status[_slot]['TX_STREAM_ID']:
logger.info('(%s) CALL DROPPED ON EGRESS WITH STREAM ID %s ON TGID %s BY SYSTEM TS2 ACL', _target, int_id(_stream_id), int_id(_dst_id))
_target_status[_slot]['TX_STREAM_ID'] = _stream_id
continue
# Record this stuff for later
# Is this a new call stream?
if new_stream:
# Record the DST TGID and Stream ID
_target_status[_slot]['TX_START'] = pkt_time
_target_status[_slot]['TX_TGID'] = _dst_id
_target_status[_slot]['TX_RFS'] = _rf_src
_target_status[_slot]['TX_PEER'] = _peer_id
_target_status[_slot]['TX_STREAM_ID'] = _stream_id
_target_status[_slot]['TX_TIME'] = pkt_time
systems[_target].send_system(_data)
#logger.debug('(%s) Packet routed to system: %s', self._system, _target)
# Mark status variables for use later
self.STATUS[_slot]['RX_RFS'] = _rf_src
self.STATUS[_slot]['RX_SEQ'] = _seq
self.STATUS[_slot]['RX_TYPE'] = _dtype_vseq
self.STATUS[_slot]['RX_TGID'] = _dst_id
self.STATUS[_slot]['RX_TIME'] = pkt_time
self.STATUS[_slot]['RX_STREAM_ID'] = _stream_id
#************************************************
# MAIN PROGRAM LOOP STARTS HERE
#************************************************
if __name__ == '__main__':
import argparse
import sys
import os
import signal
from dmr_utils3.utils import try_download, mk_id_dict
# Change the current directory to the location of the application
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually hblink.cfg)')
parser.add_argument('-l', '--logging', action='store', dest='LOG_LEVEL', help='Override config file logging level.')
cli_args = parser.parse_args()
# Ensure we have a path for the config file, if one wasn't specified, then use the default (top of file)
if not cli_args.CONFIG_FILE:
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/hblink.cfg'
# Call the external routine to build the configuration dictionary
CONFIG = config.build_config(cli_args.CONFIG_FILE)
# Start the system logger
if cli_args.LOG_LEVEL:
CONFIG['LOGGER']['LOG_LEVEL'] = cli_args.LOG_LEVEL
logger = log.config_logging(CONFIG['LOGGER'])
logger.info('\n\nCopyright (c) 2013, 2014, 2015, 2016, 2018, 2019\n\tThe Regents of the K0USY Group. All rights reserved.\n')
logger.debug('Logging system started, anything from here on gets logged')
# Set up the signal handler
def sig_handler(_signal, _frame):
logger.info('SHUTDOWN: BRIDGE_ALL IS TERMINATING WITH SIGNAL %s', str(_signal))
hblink_handler(_signal, _frame)
logger.info('SHUTDOWN: ALL SYSTEM HANDLERS EXECUTED - STOPPING REACTOR')
reactor.stop()
# Set signal handers so that we can gracefully exit if need be
for sig in [signal.SIGTERM, signal.SIGINT]:
signal.signal(sig, sig_handler)
# Create the name-number mapping dictionaries
peer_ids, subscriber_ids, talkgroup_ids = mk_aliases(CONFIG)
# INITIALIZE THE REPORTING LOOP
report_server = config_reports(CONFIG, reportFactory)
# HBlink instance creation
logger.info('HBlink \'bridge_all.py\' -- SYSTEM STARTING...')
for system in CONFIG['SYSTEMS']:
if CONFIG['SYSTEMS'][system]['ENABLED']:
if CONFIG['SYSTEMS'][system]['MODE'] == 'OPENBRIDGE':
logger.critical('%s FATAL: Instance is mode \'OPENBRIDGE\', \n\t\t...Which would be tragic for Bridge All, since it carries multiple call\n\t\tstreams simultaneously. bridge_all.py onlyl works with MMDVM-based systems', system)
sys.exit('bridge_all.py cannot function with systems that are not MMDVM devices. System {} is configured as an OPENBRIDGE'.format(system))
else:
systems[system] = bridgeallSYSTEM(system, CONFIG, report_server)
reactor.listenUDP(CONFIG['SYSTEMS'][system]['PORT'], systems[system], interface=CONFIG['SYSTEMS'][system]['IP'])
logger.debug('%s instance created: %s, %s', CONFIG['SYSTEMS'][system]['MODE'], system, systems[system])
reactor.run()

View File

@ -1,398 +0,0 @@
# PROGRAM-WIDE PARAMETERS GO HERE
# PATH - working path for files, leave it alone unless you NEED to change it
# PING_TIME - the interval that peers will ping the master, and re-try registraion
# - how often the Master maintenance loop runs
# MAX_MISSED - how many pings are missed before we give up and re-register
# - number of times the master maintenance loop runs before de-registering a peer
#
# ACLs:
#
# Access Control Lists are a very powerful tool for administering your system.
# But they consume packet processing time. Disable them if you are not using them.
# But be aware that, as of now, the configuration stanzas still need the ACL
# sections configured even if you're not using them.
#
# REGISTRATION ACLS ARE ALWAYS USED, ONLY SUBSCRIBER AND TGID MAY BE DISABLED!!!
#
# The 'action' May be PERMIT|DENY
# Each entry may be a single radio id, or a hypenated range (e.g. 1-2999)
# Format:
# ACL = 'action:id|start-end|,id|start-end,....'
# --for example--
# SUB_ACL: DENY:1,1000-2000,4500-60000,17
#
# ACL Types:
# REG_ACL: peer radio IDs for registration (only used on HBP master systems)
# SUB_ACL: subscriber IDs for end-users
# TGID_TS1_ACL: destination talkgroup IDs on Timeslot 1
# TGID_TS2_ACL: destination talkgroup IDs on Timeslot 2
#
# ACLs may be repeated for individual systems if needed for granularity
# Global ACLs will be processed BEFORE the system level ACLs
# Packets will be matched against all ACLs, GLOBAL first. If a packet 'passes'
# All elements, processing continues. Packets are discarded at the first
# negative match, or 'reject' from an ACL element.
#
# If you do not wish to use ACLs, set them to 'PERMIT:ALL'
# TGID_TS1_ACL in the global stanza is used for OPENBRIDGE systems, since all
# traffic is passed as TS 1 between OpenBridges
[GLOBAL]
PATH: ./
PING_TIME: 5
MAX_MISSED: 3
USE_ACL: True
REG_ACL: PERMIT:ALL
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
# APRS - BY IU7IGU
# Enabling "APRS" will configure APRS-Beaconing of Master's connection
# like repeater and hotspots.
# REPORT_INTERVAL in Minute (ALLOW only > 3 Minutes)
# CALLSIGN: Callsign that will pubblish data on aprs server
# MESSAGE: This message will print on APRS description together RX and TX Frequency
[APRS]
ENABLED: False
REPORT_INTERVAL: 15
CALLSIGN:HB1LNK-11
SERVER:euro.aprs2.net
MESSAGE:Connesso ad HBLINK
# NOT YET WORKING: NETWORK REPORTING CONFIGURATION
# Enabling "REPORT" will configure a socket-based reporting
# system that will send the configuration and other items
# to a another process (local or remote) that may process
# the information for some useful purpose, like a web dashboard.
#
# REPORT - True to enable, False to disable
# REPORT_INTERVAL - Seconds between reports
# REPORT_PORT - TCP port to listen on if "REPORT_NETWORKS" = NETWORK
# REPORT_CLIENTS - comma separated list of IPs you will allow clients
# to connect on. Entering a * will allow all.
#
# ****FOR NOW MUST BE TRUE - USE THE LOOPBACK IF YOU DON'T USE THIS!!!****
[REPORTS]
REPORT: True
REPORT_INTERVAL: 60
REPORT_PORT: 4321
REPORT_CLIENTS: 127.0.0.1
# SYSTEM LOGGER CONFIGURAITON
# This allows the logger to be configured without chaning the individual
# python logger stuff. LOG_FILE should be a complete path/filename for *your*
# system -- use /dev/null for non-file handlers.
# LOG_HANDLERS may be any of the following, please, no spaces in the
# list if you use several:
# null
# console
# console-timed
# file
# file-timed
# syslog
# LOG_LEVEL may be any of the standard syslog logging levels, though
# as of now, DEBUG, INFO, WARNING and CRITICAL are the only ones
# used.
#
[LOGGER]
LOG_FILE: /tmp/hblink.log
LOG_HANDLERS: console-timed
LOG_LEVEL: DEBUG
LOG_NAME: HBlink
# DOWNLOAD AND IMPORT SUBSCRIBER, PEER and TGID ALIASES
# Ok, not the TGID, there's no master list I know of to download
# This is intended as a facility for other applcations built on top of
# HBlink to use, and will NOT be used in HBlink directly.
# STALE_DAYS is the number of days since the last download before we
# download again. Don't be an ass and change this to less than a few days.
[ALIASES]
TRY_DOWNLOAD: True
PATH: ./
PEER_FILE: peer_ids.json
SUBSCRIBER_FILE: subscriber_ids.json
TGID_FILE: talkgroup_ids.json
PEER_URL: https://www.radioid.net/static/rptrs.json
SUBSCRIBER_URL: https://www.radioid.net/static/users.json
STALE_DAYS: 1
# GPS/Data Application - by KF7EEL
# Configure the settings for the DMR GPS to APRS position application here.
#
# DATA_DMR_ID - This is the DMR ID that users send DMR GPS data.
# CALL_TYPE - group, unit, or both. Group if you want users to send data to a talkgroup,
# unit if you want users to send data as a private call, or both if you want both options.
# USER_APRS_SSID - Default APRS SSID assigned to user APRS positions.
# USER_APRS_COMMENT - Default Comment attached to user APRS positions.
# APRS_LOGIN_CALL, PASSCODE, SERVER, and PORT - Login settings for APRS-IS.
[GPS_DATA]
DATA_DMR_ID: 9099
CALL_TYPE: both
USER_APRS_SSID: 15
USER_APRS_COMMENT: HBLink3 D-APRS -
# Setting APRS_LOGIN_CALL to N0CALL will cause the gateway to not upload packets to APRS server.
APRS_LOGIN_CALL: N0CALL
APRS_LOGIN_PASSCODE: 12345
APRS_SERVER: rotate.aprs2.net
APRS_PORT: 14580
# The following settings are only applicable if you are using the gps_data_beacon_igate script.
# They do not affect the operation gps_data itself.
# Time in minutes.
IGATE_BEACON_TIME = 45
IGATE_BEACON_COMMENT = HBLink3 D-APRS Gateway
IGATE_BEACON_ICON = /I
IGATE_LATITUDE = 0000.00N
IGATE_LONGITUDE = 00000.00W
# User settings file, MUST configure using absolute path.
USER_SETTINGS_FILE: /path/to/user_settings.txt
# The APRS filter below is used for the message received script. See http://www.aprs-is.net/javAPRSFilter.aspx for details
# about APRS filters.
APRS_RECEIVE_LOGIN_CALL: N0CALL-1
APRS_FILTER: r/47/-120/500 t/m
# The email gateway settingns below are OPTIONAL. They are NOT REQUIRED if you don't want
# to enable the email gateway. Leave as is to disable.
EMAIL_SENDER:
EMAIL_PASSWORD:
SMTP_SERVER: smtp.gmail.com
SMTP_PORT: 465
# The options below are required for operation of the dashboard and will cause errors in gps_data.py
# if configured wrong. Leave them as default unless you know what you are doing.
# If you do change, you must use absolute paths.
LOCATION_FILE: /tmp/gps_data_user_loc.txt
BULLETIN_BOARD_FILE: /tmp/gps_data_user_bb.txt
MAILBOX_FILE: /tmp/gps_data_user_mailbox.txt
EMERGENCY_SOS_FILE: /tmp/gps_data_user_sos.txt
# The following options are used for the dashboard. The dashboard is optional.
# Title of the Dashboard
DASHBOARD_TITLE: HBLink3 D-APRS Dashboard
# Logo used on dashboard page
LOGO: https://raw.githubusercontent.com/kf7eel/hblink3/gps/HBlink.png
# Port to run server
DASH_PORT: 8092
# IP to run server on
DASH_HOST: 127.0.0.1
#Description of dashboard to show on main page
DESCRIPTION: Welcome to the dashboard.
# Gateway contact info displayed on about page.
CONTACT_NAME: your name
CONTACT_CALL: N0CALL
CONTACT_EMAIL: email@example.org
CONTACT_WEBSITE: https://hbl.ink
# Time format for display
TIME_FORMAT: %%H:%%M:%%S - %%m/%%d/%%y
# Center dashboard map over these coordinates
MAP_CENTER_LAT: 47.00
MAP_CENTER_LON: -120.00
ZOOM_LEVEL: 7
# List and preview of some map themes at http://leaflet-extras.github.io/leaflet-providers/preview/
# The following are options for map themes and just work, you should use one of these: “OpenStreetMap”, “Stamen” (Terrain, Toner, and Watercolor),
MAP_THEME: Stamen Toner
# RSS feed link, shows in the link section of each RSS item.
RSS_LINK: http://localhost:8092
# OPENBRIDGE INSTANCES - DUPLICATE SECTION FOR MULTIPLE CONNECTIONS
# OpenBridge is a protocol originall created by DMR+ for connection between an
# IPSC2 server and Brandmeister. It has been implemented here at the suggestion
# of the Brandmeister team as a way to legitimately connect HBlink to the
# Brandemiester network.
# It is recommended to name the system the ID of the Brandmeister server that
# it connects to, but is not necessary. TARGET_IP and TARGET_PORT are of the
# Brandmeister or IPSC2 server you are connecting to. PASSPHRASE is the password
# that must be agreed upon between you and the operator of the server you are
# connecting to. NETWORK_ID is a number in the format of a DMR Radio ID that
# will be sent to the other server to identify this connection.
# other parameters follow the other system types.
#
# ACLs:
# OpenBridge does not 'register', so registration ACL is meaningless.
# Proper OpenBridge passes all traffic on TS1.
# HBlink can extend OPB to use both slots for unit calls only.
# Setting "BOTH_SLOTS" True ONLY affects unit traffic!
# Otherwise ACLs work as described in the global stanza
[OBP-1]
MODE: OPENBRIDGE
ENABLED: False
IP:
PORT: 62035
NETWORK_ID: 3129100
PASSPHRASE: password
TARGET_IP: 1.2.3.4
TARGET_PORT: 62035
BOTH_SLOTS: True
USE_ACL: True
SUB_ACL: DENY:1
TGID_ACL: PERMIT:ALL
# MASTER INSTANCES - DUPLICATE SECTION FOR MULTIPLE MASTERS
# HomeBrew Protocol Master instances go here.
# IP may be left blank if there's one interface on your system.
# Port should be the port you want this master to listen on. It must be unique
# and unused by anything else.
# Repeat - if True, the master repeats traffic to peers, False, it does nothing.
#
# MAX_PEERS -- maximun number of peers that may be connect to this master
# at any given time. This is very handy if you're allowing hotspots to
# connect, or using a limited computer like a Raspberry Pi.
#
# ACLs:
# See comments in the GLOBAL stanza
[MASTER-1]
MODE: MASTER
ENABLED: True
# The APRS setting below has to do with the beaconing of PEER conections, and not GPS positions
# from radios. This setting will not affect gps_data.py
APRS: False
REPEAT: True
MAX_PEERS: 10
EXPORT_AMBE: False
IP:
PORT: 54000
PASSPHRASE: s3cr37w0rd
GROUP_HANGTIME: 5
USE_ACL: True
REG_ACL: DENY:1
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
[D-APRS]
MODE: MASTER
ENABLED: True
REPEAT: True
MAX_PEERS: 2
EXPORT_AMBE: False
IP:
PORT: 54070
PASSPHRASE: passw0rd
GROUP_HANGTIME: 5
USE_ACL: True
REG_ACL: DENY:1
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
# PEER INSTANCES - DUPLICATE SECTION FOR MULTIPLE PEERS
# There are a LOT of errors in the HB Protocol specifications on this one!
# MOST of these items are just strings and will be properly dealt with by the program
# The TX & RX Frequencies are 9-digit numbers, and are the frequency in Hz.
# Latitude is an 8-digit unsigned floating point number.
# Longitude is a 9-digit signed floating point number.
# Height is in meters
# Setting Loose to True relaxes the validation on packets received from the master.
# This will allow HBlink to connect to a non-compliant system such as XLXD, DMR+ etc.
#
# ACLs:
# See comments in the GLOBAL stanza
[REPEATER-1]
MODE: PEER
ENABLED: False
LOOSE: False
EXPORT_AMBE: False
IP:
PORT: 54001
MASTER_IP: 172.16.1.1
MASTER_PORT: 54000
PASSPHRASE: homebrew
CALLSIGN: W1ABC
RADIO_ID: 312000
RX_FREQ: 449000000
TX_FREQ: 444000000
TX_POWER: 25
COLORCODE: 1
SLOTS: 1
LATITUDE: 38.0000
LONGITUDE: -095.0000
HEIGHT: 75
LOCATION: Anywhere, USA
DESCRIPTION: This is a cool repeater
URL: www.w1abc.org
SOFTWARE_ID: 20170620
PACKAGE_ID: MMDVM_HBlink
GROUP_HANGTIME: 5
OPTIONS:
USE_ACL: True
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
[ECHO]
MODE: PEER
ENABLED: True
LOOSE: False
EXPORT_AMBE: False
IP:
PORT: 54073
MASTER_IP: localhost
MASTER_PORT: 54072
passphrase: passw0rd
CALLSIGN: ECHO
RADIO_ID: 9999
RX_FREQ: 000000000
TX_FREQ: 000000000
TX_POWER: 0
COLORCODE: 1
SLOTS: 1
LATITUDE: 00.0000
LONGITUDE: 000.0000
HEIGHT: 0
LOCATION: This Server
DESCRIPTION: Echo Server
URL: www.github.com/kf7eel/hblink3
SOFTWARE_ID: 20170620
PACKAGE_ID: MMDVM_HBlink
GROUP_HANGTIME: 5
OPTIONS:
USE_ACL: True
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
[XLX-1]
MODE: XLXPEER
ENABLED: False
LOOSE: True
EXPORT_AMBE: False
IP:
PORT: 54002
MASTER_IP: 172.16.1.1
MASTER_PORT: 62030
PASSPHRASE: passw0rd
CALLSIGN: W1ABC
RADIO_ID: 312000
RX_FREQ: 449000000
TX_FREQ: 444000000
TX_POWER: 25
COLORCODE: 1
SLOTS: 1
LATITUDE: 38.0000
LONGITUDE: -095.0000
HEIGHT: 75
LOCATION: Anywhere, USA
DESCRIPTION: This is a cool repeater
URL: www.w1abc.org
SOFTWARE_ID: 20170620
PACKAGE_ID: MMDVM_HBlink
GROUP_HANGTIME: 5
XLXMODULE: 4004
USE_ACL: True
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL

File diff suppressed because it is too large Load Diff

354
config.py
View File

@ -1,354 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2018 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
This module generates the configuration data structure for hblink.py and
assoicated programs that use it. It has been seaparated into a different
module so as to keep hblink.py easeier to navigate. This file only needs
updated if the items in the main configuraiton file (usually hblink.cfg)
change.
'''
import configparser
import sys
import const
from socket import gethostbyname
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
__author__ = 'Cortney T. Buffington, N0MJS'
__copyright__ = 'Copyright (c) 2016-2018 Cortney T. Buffington, N0MJS and the K0USY Group'
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
__license__ = 'GNU GPLv3'
__maintainer__ = 'Cort Buffington, N0MJS'
__email__ = 'n0mjs@me.com'
# Processing of ALS goes here. It's separated from the acl_build function because this
# code is hblink config-file format specific, and acl_build is abstracted
def process_acls(_config):
# Global registration ACL
_config['GLOBAL']['REG_ACL'] = acl_build(_config['GLOBAL']['REG_ACL'], const.PEER_MAX)
# Global subscriber and TGID ACLs
for acl in ['SUB_ACL', 'TG1_ACL', 'TG2_ACL']:
_config['GLOBAL'][acl] = acl_build(_config['GLOBAL'][acl], const.ID_MAX)
# System level ACLs
for system in _config['SYSTEMS']:
# Registration ACLs (which make no sense for peer systems)
if _config['SYSTEMS'][system]['MODE'] == 'MASTER':
_config['SYSTEMS'][system]['REG_ACL'] = acl_build(_config['SYSTEMS'][system]['REG_ACL'], const.PEER_MAX)
# Subscriber and TGID ACLs (valid for all system types)
for acl in ['SUB_ACL', 'TG1_ACL', 'TG2_ACL']:
_config['SYSTEMS'][system][acl] = acl_build(_config['SYSTEMS'][system][acl], const.ID_MAX)
# Create an access control list that is programatically useable from human readable:
# ORIGINAL: 'DENY:1-5,3120101,3120124'
# PROCESSED: (False, set([(1, 5), (3120124, 3120124), (3120101, 3120101)]))
def acl_build(_acl, _max):
if not _acl:
return(True, set((const.ID_MIN, _max)))
acl = [] #set()
sections = _acl.split(':')
if sections[0] == 'PERMIT':
action = True
else:
action = False
for entry in sections[1].split(','):
if entry == 'ALL':
acl.append((const.ID_MIN, _max))
break
elif '-' in entry:
start,end = entry.split('-')
start,end = int(start), int(end)
if (const.ID_MIN <= start <= _max) or (const.ID_MIN <= end <= _max):
acl.append((start, end))
else:
sys.exit('ACL CREATION ERROR, VALUE OUT OF RANGE ({} - {})IN RANGE-BASED ENTRY: {}'.format(const.ID_MIN, _max, entry))
else:
id = int(entry)
if (const.ID_MIN <= id <= _max):
acl.append((id, id))
else:
sys.exit('ACL CREATION ERROR, VALUE OUT OF RANGE ({} - {}) IN SINGLE ID ENTRY: {}'.format(const.ID_MIN, _max, entry))
return (action, acl)
def build_config(_config_file):
config = configparser.ConfigParser()
if not config.read(_config_file):
sys.exit('Configuration file \''+_config_file+'\' is not a valid configuration file! Exiting...')
CONFIG = {}
CONFIG['GLOBAL'] = {}
CONFIG['REPORTS'] = {}
CONFIG['LOGGER'] = {}
CONFIG['GPS_DATA'] = {}
CONFIG['ALIASES'] = {}
CONFIG['SYSTEMS'] = {}
try:
for section in config.sections():
if section == 'GLOBAL':
CONFIG['GLOBAL'].update({
'PATH': config.get(section, 'PATH'),
'PING_TIME': config.getint(section, 'PING_TIME'),
'MAX_MISSED': config.getint(section, 'MAX_MISSED'),
'USE_ACL': config.get(section, 'USE_ACL'),
'REG_ACL': config.get(section, 'REG_ACL'),
'SUB_ACL': config.get(section, 'SUB_ACL'),
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
'TG2_ACL': config.get(section, 'TGID_TS2_ACL')
})
elif section == 'REPORTS':
CONFIG['REPORTS'].update({
'REPORT': config.getboolean(section, 'REPORT'),
'REPORT_INTERVAL': config.getint(section, 'REPORT_INTERVAL'),
'REPORT_PORT': config.getint(section, 'REPORT_PORT'),
'REPORT_CLIENTS': config.get(section, 'REPORT_CLIENTS').split(',')
})
elif section == 'LOGGER':
CONFIG['LOGGER'].update({
'LOG_FILE': config.get(section, 'LOG_FILE'),
'LOG_HANDLERS': config.get(section, 'LOG_HANDLERS'),
'LOG_LEVEL': config.get(section, 'LOG_LEVEL'),
'LOG_NAME': config.get(section, 'LOG_NAME')
})
if not CONFIG['LOGGER']['LOG_FILE']:
CONFIG['LOGGER']['LOG_FILE'] = '/dev/null'
elif section == 'GPS_DATA':
CONFIG['GPS_DATA'].update({
'DATA_DMR_ID': config.get(section, 'DATA_DMR_ID'),
'USER_APRS_SSID': config.get(section, 'USER_APRS_SSID'),
'CALL_TYPE': config.get(section, 'CALL_TYPE'),
'USER_APRS_COMMENT': config.get(section, 'USER_APRS_COMMENT'),
'APRS_LOGIN_CALL': config.get(section, 'APRS_LOGIN_CALL'),
'APRS_LOGIN_PASSCODE': config.get(section, 'APRS_LOGIN_PASSCODE'),
'APRS_SERVER': config.get(section, 'APRS_SERVER'),
'APRS_PORT': config.get(section, 'APRS_PORT'),
'IGATE_BEACON_TIME': config.get(section, 'IGATE_BEACON_TIME'),
'IGATE_BEACON_ICON': config.get(section, 'IGATE_BEACON_ICON'),
'IGATE_BEACON_COMMENT': config.get(section, 'IGATE_BEACON_COMMENT'),
'IGATE_LATITUDE': config.get(section, 'IGATE_LATITUDE'),
'IGATE_LONGITUDE': config.get(section, 'IGATE_LONGITUDE'),
'EMAIL_SENDER': config.get(section, 'EMAIL_SENDER'),
'EMAIL_PASSWORD': config.get(section, 'EMAIL_PASSWORD'),
'SMTP_SERVER': config.get(section, 'SMTP_SERVER'),
'SMTP_PORT': config.get(section, 'SMTP_PORT'),
'LOCATION_FILE': config.get(section, 'LOCATION_FILE'),
'BULLETIN_BOARD_FILE': config.get(section, 'BULLETIN_BOARD_FILE'),
'MAILBOX_FILE': config.get(section, 'MAILBOX_FILE'),
'EMERGENCY_SOS_FILE': config.get(section, 'EMERGENCY_SOS_FILE'),
'USER_SETTINGS_FILE': config.get(section, 'USER_SETTINGS_FILE'),
})
if not CONFIG['LOGGER']['LOG_FILE']:
CONFIG['LOGGER']['LOG_FILE'] = '/dev/null'
elif section == 'ALIASES':
CONFIG['ALIASES'].update({
'TRY_DOWNLOAD': config.getboolean(section, 'TRY_DOWNLOAD'),
'PATH': config.get(section, 'PATH'),
'PEER_FILE': config.get(section, 'PEER_FILE'),
'SUBSCRIBER_FILE': config.get(section, 'SUBSCRIBER_FILE'),
'TGID_FILE': config.get(section, 'TGID_FILE'),
'PEER_URL': config.get(section, 'PEER_URL'),
'SUBSCRIBER_URL': config.get(section, 'SUBSCRIBER_URL'),
'STALE_TIME': config.getint(section, 'STALE_DAYS') * 86400,
})
elif config.getboolean(section, 'ENABLED'):
if config.get(section, 'MODE') == 'PEER':
CONFIG['SYSTEMS'].update({section: {
'MODE': config.get(section, 'MODE'),
'ENABLED': config.getboolean(section, 'ENABLED'),
'LOOSE': config.getboolean(section, 'LOOSE'),
'SOCK_ADDR': (gethostbyname(config.get(section, 'IP')), config.getint(section, 'PORT')),
'IP': gethostbyname(config.get(section, 'IP')),
'PORT': config.getint(section, 'PORT'),
'MASTER_SOCKADDR': (gethostbyname(config.get(section, 'MASTER_IP')), config.getint(section, 'MASTER_PORT')),
'MASTER_IP': gethostbyname(config.get(section, 'MASTER_IP')),
'MASTER_PORT': config.getint(section, 'MASTER_PORT'),
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE'), 'utf-8'),
'CALLSIGN': bytes(config.get(section, 'CALLSIGN').ljust(8)[:8], 'utf-8'),
'RADIO_ID': config.getint(section, 'RADIO_ID').to_bytes(4, 'big'),
'RX_FREQ': bytes(config.get(section, 'RX_FREQ').ljust(9)[:9], 'utf-8'),
'TX_FREQ': bytes(config.get(section, 'TX_FREQ').ljust(9)[:9], 'utf-8'),
'TX_POWER': bytes(config.get(section, 'TX_POWER').rjust(2,'0'), 'utf-8'),
'COLORCODE': bytes(config.get(section, 'COLORCODE').rjust(2,'0'), 'utf-8'),
'LATITUDE': bytes(config.get(section, 'LATITUDE').ljust(8)[:8], 'utf-8'),
'LONGITUDE': bytes(config.get(section, 'LONGITUDE').ljust(9)[:9], 'utf-8'),
'HEIGHT': bytes(config.get(section, 'HEIGHT').rjust(3,'0'), 'utf-8'),
'LOCATION': bytes(config.get(section, 'LOCATION').ljust(20)[:20], 'utf-8'),
'DESCRIPTION': bytes(config.get(section, 'DESCRIPTION').ljust(19)[:19], 'utf-8'),
'SLOTS': bytes(config.get(section, 'SLOTS'), 'utf-8'),
'URL': bytes(config.get(section, 'URL').ljust(124)[:124], 'utf-8'),
'SOFTWARE_ID': bytes(config.get(section, 'SOFTWARE_ID').ljust(40)[:40], 'utf-8'),
'PACKAGE_ID': bytes(config.get(section, 'PACKAGE_ID').ljust(40)[:40], 'utf-8'),
'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME'),
'OPTIONS': bytes(config.get(section, 'OPTIONS'), 'utf-8'),
'USE_ACL': config.getboolean(section, 'USE_ACL'),
'SUB_ACL': config.get(section, 'SUB_ACL'),
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
'TG2_ACL': config.get(section, 'TGID_TS2_ACL')
}})
CONFIG['SYSTEMS'][section].update({'STATS': {
'CONNECTION': 'NO', # NO, RTPL_SENT, AUTHENTICATED, CONFIG-SENT, YES
'CONNECTED': None,
'PINGS_SENT': 0,
'PINGS_ACKD': 0,
'NUM_OUTSTANDING': 0,
'PING_OUTSTANDING': False,
'LAST_PING_TX_TIME': 0,
'LAST_PING_ACK_TIME': 0,
}})
if config.get(section, 'MODE') == 'XLXPEER':
CONFIG['SYSTEMS'].update({section: {
'MODE': config.get(section, 'MODE'),
'ENABLED': config.getboolean(section, 'ENABLED'),
'LOOSE': config.getboolean(section, 'LOOSE'),
'SOCK_ADDR': (gethostbyname(config.get(section, 'IP')), config.getint(section, 'PORT')),
'IP': gethostbyname(config.get(section, 'IP')),
'PORT': config.getint(section, 'PORT'),
'MASTER_SOCKADDR': (gethostbyname(config.get(section, 'MASTER_IP')), config.getint(section, 'MASTER_PORT')),
'MASTER_IP': gethostbyname(config.get(section, 'MASTER_IP')),
'MASTER_PORT': config.getint(section, 'MASTER_PORT'),
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE'), 'utf-8'),
'CALLSIGN': bytes(config.get(section, 'CALLSIGN').ljust(8)[:8], 'utf-8'),
'RADIO_ID': config.getint(section, 'RADIO_ID').to_bytes(4, 'big'),
'RX_FREQ': bytes(config.get(section, 'RX_FREQ').ljust(9)[:9], 'utf-8'),
'TX_FREQ': bytes(config.get(section, 'TX_FREQ').ljust(9)[:9], 'utf-8'),
'TX_POWER': bytes(config.get(section, 'TX_POWER').rjust(2,'0'), 'utf-8'),
'COLORCODE': bytes(config.get(section, 'COLORCODE').rjust(2,'0'), 'utf-8'),
'LATITUDE': bytes(config.get(section, 'LATITUDE').ljust(8)[:8], 'utf-8'),
'LONGITUDE': bytes(config.get(section, 'LONGITUDE').ljust(9)[:9], 'utf-8'),
'HEIGHT': bytes(config.get(section, 'HEIGHT').rjust(3,'0'), 'utf-8'),
'LOCATION': bytes(config.get(section, 'LOCATION').ljust(20)[:20], 'utf-8'),
'DESCRIPTION': bytes(config.get(section, 'DESCRIPTION').ljust(19)[:19], 'utf-8'),
'SLOTS': bytes(config.get(section, 'SLOTS'), 'utf-8'),
'URL': bytes(config.get(section, 'URL').ljust(124)[:124], 'utf-8'),
'SOFTWARE_ID': bytes(config.get(section, 'SOFTWARE_ID').ljust(40)[:40], 'utf-8'),
'PACKAGE_ID': bytes(config.get(section, 'PACKAGE_ID').ljust(40)[:40], 'utf-8'),
'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME'),
'XLXMODULE': config.getint(section, 'XLXMODULE'),
'OPTIONS': '',
'USE_ACL': config.getboolean(section, 'USE_ACL'),
'SUB_ACL': config.get(section, 'SUB_ACL'),
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
'TG2_ACL': config.get(section, 'TGID_TS2_ACL')
}})
CONFIG['SYSTEMS'][section].update({'XLXSTATS': {
'CONNECTION': 'NO', # NO, RTPL_SENT, AUTHENTICATED, CONFIG-SENT, YES
'CONNECTED': None,
'PINGS_SENT': 0,
'PINGS_ACKD': 0,
'NUM_OUTSTANDING': 0,
'PING_OUTSTANDING': False,
'LAST_PING_TX_TIME': 0,
'LAST_PING_ACK_TIME': 0,
}})
elif config.get(section, 'MODE') == 'MASTER':
CONFIG['SYSTEMS'].update({section: {
'MODE': config.get(section, 'MODE'),
'ENABLED': config.getboolean(section, 'ENABLED'),
'REPEAT': config.getboolean(section, 'REPEAT'),
'MAX_PEERS': config.getint(section, 'MAX_PEERS'),
'IP': gethostbyname(config.get(section, 'IP')),
'PORT': config.getint(section, 'PORT'),
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE'), 'utf-8'),
'GROUP_HANGTIME': config.getint(section, 'GROUP_HANGTIME'),
'USE_ACL': config.getboolean(section, 'USE_ACL'),
'REG_ACL': config.get(section, 'REG_ACL'),
'SUB_ACL': config.get(section, 'SUB_ACL'),
'TG1_ACL': config.get(section, 'TGID_TS1_ACL'),
'TG2_ACL': config.get(section, 'TGID_TS2_ACL')
}})
CONFIG['SYSTEMS'][section].update({'PEERS': {}})
elif config.get(section, 'MODE') == 'OPENBRIDGE':
CONFIG['SYSTEMS'].update({section: {
'MODE': config.get(section, 'MODE'),
'ENABLED': config.getboolean(section, 'ENABLED'),
'NETWORK_ID': config.getint(section, 'NETWORK_ID').to_bytes(4, 'big'),
'IP': gethostbyname(config.get(section, 'IP')),
'PORT': config.getint(section, 'PORT'),
'PASSPHRASE': bytes(config.get(section, 'PASSPHRASE').ljust(20,'\x00')[:20], 'utf-8'),
'TARGET_SOCK': (gethostbyname(config.get(section, 'TARGET_IP')), config.getint(section, 'TARGET_PORT')),
'TARGET_IP': gethostbyname(config.get(section, 'TARGET_IP')),
'TARGET_PORT': config.getint(section, 'TARGET_PORT'),
'BOTH_SLOTS': config.getboolean(section, 'BOTH_SLOTS'),
'USE_ACL': config.getboolean(section, 'USE_ACL'),
'SUB_ACL': config.get(section, 'SUB_ACL'),
'TG1_ACL': config.get(section, 'TGID_ACL'),
'TG2_ACL': 'PERMIT:ALL'
}})
except configparser.Error as err:
sys.exit('Error processing configuration file -- {}'.format(err))
process_acls(CONFIG)
return CONFIG
# Used to run this file direclty and print the config,
# which might be useful for debugging
if __name__ == '__main__':
import sys
import os
import argparse
from pprint import pprint
from dmr_utils3.utils import int_id
# Change the current directory to the location of the application
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually hblink.cfg)')
cli_args = parser.parse_args()
# Ensure we have a path for the config file, if one wasn't specified, then use the execution directory
if not cli_args.CONFIG_FILE:
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/hblink.cfg'
CONFIG = build_config(cli_args.CONFIG_FILE)
pprint(CONFIG)
def acl_check(_id, _acl):
id = int_id(_id)
for entry in _acl[1]:
if entry[0] <= id <= entry[1]:
return _acl[0]
return not _acl[0]
print(acl_check(b'\x00\x01\x37', CONFIG['GLOBAL']['TG1_ACL']))

83
config_doc.md Normal file
View File

@ -0,0 +1,83 @@
# Configuration
## [Home](https://kf7eel.github.io/hblink3/) | [Configuration](/hblink3/config_doc.html) | [API Documentation](https://kf7eel.github.io/hblink3/api_doc.html) | [HBlink Website](https://hblink-org.github.io/)
----
## full_bridge.cfg
DATA_DMR_ID and CALL_TYPE, the DMR ID of the gateway. Call type specifies if you want to receive private data or group data. can be set to both to receive private and group data. Options: unit, group, both.
UNIT_SMS_TS. This is the default timeslot that an SMS is sent on. Every time a user keys the radio, whether a private call or talkgroup, the server saves the timeslot that the user is on. By default, an SMS is routed to the last known timeslot of a user. When the last timeslot is not know, UNIT_SMS_TS is used. For example, if the user has not transmitted in a long time, and APRS message is received, the generated SMS will be sent on UNIT_SMS_TS.
### APRS Configuration
USER_APRS_SSID and USER_APRS_COMMENT, the default SSID and coment for users. Users can change this in the dashboard or via SMS command.
APRS_LOGIN_CALL, APRS_LOGIN_PASSCODE, APRS_SERVER, and APRS_PORT, configuration used to login to an APRS server.
APRS_FILTER, sent to server for receiving specific packets. See [http://www.aprs-is.net/javAPRSFilter.aspx](http://www.aprs-is.net/javAPRSFilter.aspx) for filter options.
IGATE_, configuration for uploading the position of the gateway to APRS-IS. When the gateway uploads a position, APRS software such as aprs.fi will see it as an Igate. This is useful if you want aprs.fi or other APRS software to keep statistics. Time is set in minutes. Set IGATE_BEACON_TIME to 0 to disable Igate beaconing.
### Static Positions
In September of 2020, Daniele Marra (**IU7IGU**) created a function in HBLink that creates an APRS postiion for connected PEERS (repeaters, hotpots, etc) and send it to APRS-IS. His has been modified and included with this project to give it this functionality. APRS_STATIC_REPORT_INTERVAL is how often a position for a repeater of hotspot is uploaded to APRS-IS (must be greater than 15). APRS_STATIC_MESSAGE is the comment of the APRS position.
In each MASTER stanza, you will find the option STATIC_APRS_POSITION_ENABLED. Setting this to True will cause HBLink to sent the position of connected repeaters or hotspots to APRS-IS. Setting this to False will disable sending positions of connected peers. **This option does not affect the operation of GPS positions or SMS to individual radios**, it is used only if you want a position for hotspots/repeaters on APRS.
### LOCATION_FILE, BULLETIN_BOARD_FILE, MAILBOX_FILE, EMERGENCY_SOS_FILE, USER_SETTINGS_FILE
These options specify where to save and retrieve data used by HBLink and the D-APRS dashboard. It is OK to leave these at the default value. When saved in /tmp, the files will be lost when the server reboots. Change to a different directory to prevent the loss of the files after a reboot
**USER_SETTINGS_FILE must be set. An absolute path is required.**
### API Configuration
The API allows users to interact with external applications via SMS. The API also allows users to send messages to other users on a different network/server.
Set USE_APT to True to enable it.
AUTHORIZED_TOKENS_FILE, OK to leave as default. This is the file where one time tokens are saved.
MY_SERVER_SHORTCUT, should be something short, ideally 3 or 4 letters. This is used in the authentication and sending process. Should be unique from other servers, especially if you plan on allowing public access.
SERVER_NAME, the name of your server or network. This is used to identify your server with some external applications.
USE_PUBLIC_APPS, allow your users to use publicly accessible external applications. If set to True, every time HBLink is started, it downloads the latest list of publicly accessible external applications from the URL in PUBLIC_APPS_LIST. Leave PUBLIC_APPS_LIST as the default value to use the ["official" list](https://github.com/kf7eel/hblink_sms_external_apps/blob/main/public_systems.txt).
RULES_PATH, the absolute path to your rules.py. The D-APRS dashboard uses this to authenticate incoming API data. **You MUST set this with the absolute path to rules.py**
### D-APRS Dashboard Configuration
DASHBOARD_TITLE, title displayed on dashboard page. Can be different than SERVER_NAME.
DASHBOARD_URL is used for the API, RSS feed link, etc. This MUST be accessible from the internet. Do not add a trailing /. Can be a URL to an IP address.
LOGO, link to an image file.
DASH_PORT and DASH_HOST, port and IP address to run the dashboard. If IP set to 127.0.0.1, dashboard will only be accessible on localhost.
DESCRIPTION, description of dashboard.
TIME_FORMAT, format to display time in. Can be changed from default. Default format in month, day, year.
MAP_CENTER_LAT, MAP_CENTER_LON, ZOOM_LEVEL. The Latitude and Longitude to center the map at. ZOOM_LEVEL, default zoom level to display.
MAP_THEME, theme of the map. The following are options for map themes and just work, you should use one of these: “OpenStreetMap”, “Stamen” (Terrain, Toner, and Watercolor). List and preview of some map themes at [http://leaflet-extras.github.io/leaflet-providers/preview/](List and preview of some map themes at http://leaflet-extras.github.io/leaflet-providers/preview/).
----
## rules.py
UNIT, list the names of each system that should bridge unit to unit (individual) calls..
UNIT_TIME, this is also known as unit call flood timeout. This is the amount of time to keep sending private calls to a single system before
flooding all systems in UNIT with the call. A higher value means that the subscriber is mapped to a specific system for a longer period on time (in minutes). This can be set high for systems where subscribers are not moving between systems often (such as a group of hotspots). A lower value can be set for systems that have subscribers moving between systems often (switching repeaters often).
STATIC_UNIT. There are some instances where mapping a private call to a particular system should happen every time. An example use of this would be gps_data.py, where GPS data will always go. There is no need to flood every system with this data. Adding an entry here will route private calls and data to the specified system and not the other systems. For this to work, a system in STATIC_UNIT should not also be in UNIT.
STATIC_UNIT is optional and not required.
authorized_users, stored authentication credentials for other networks/servers that can your server SMS messages (using msg_xfer mode in the API). This list is manually specified and is optional.
local_systems, information about other networks/servers or publicly accessible external applications. This list is added to the public list when HBLink starts. Use this to manually specify non public external applications or non public servers/networks. See the API documentation for more information.

View File

@ -1,74 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2018 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
These are contants used by HBlink. Rather than stuff them into the main program
file, any new constants should be placed here. It makes them easier to keep track
of and keeps hblink.py shorter.
'''
__author__ = 'Cortney T. Buffington, N0MJS'
__copyright__ = 'Copyright (c) 2016 Cortney T. Buffington, N0MJS and the K0USY Group'
__credits__ = ''
__license__ = 'GNU GPLv3'
__maintainer__ = 'Cort Buffington, N0MJS'
__email__ = 'n0mjs@me.com'
# DMR Related constants
ID_MIN = 1
ID_MAX = 16776415
# Timers
STREAM_TO = .360
# Options from the LC - used for late entry
LC_OPT = b'\x00\x00\x20'
# HomeBrew Protocol Frame Types
HBPF_VOICE = 0x0
HBPF_VOICE_SYNC = 0x1
HBPF_DATA_SYNC = 0x2
HBPF_SLT_VHEAD = 0x1
HBPF_SLT_VTERM = 0x2
# HomeBrew Protocol Commands
DMRA = b'DMRA'
DMRD = b'DMRD'
MSTCL = b'MSTCL'
MSTNAK = b'MSTNAK'
MSTPONG = b'MSTPONG'
MSTN = b'MSTN'
MSTP = b'MSTP'
MSTC = b'MSTC'
RPTL = b'RPTL'
RPTPING = b'RPTPING'
RPTCL = b'RPTCL'
RPTL = b'RPTL'
RPTACK = b'RPTACK'
RPTK = b'RPTK'
RPTC = b'RPTC'
RPTP = b'RPTP'
RPTA = b'RPTA'
RPTO = b'RPTO'
# Higheset peer ID permitted by HBP
PEER_MAX = 4294967295

BIN
emergency_screen.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

View File

@ -1,307 +0,0 @@
# PROGRAM-WIDE PARAMETERS GO HERE
# PATH - working path for files, leave it alone unless you NEED to change it
# PING_TIME - the interval that peers will ping the master, and re-try registraion
# - how often the Master maintenance loop runs
# MAX_MISSED - how many pings are missed before we give up and re-register
# - number of times the master maintenance loop runs before de-registering a peer
#
# ACLs:
#
# Access Control Lists are a very powerful tool for administering your system.
# But they consume packet processing time. Disable them if you are not using them.
# But be aware that, as of now, the configuration stanzas still need the ACL
# sections configured even if you're not using them.
#
# REGISTRATION ACLS ARE ALWAYS USED, ONLY SUBSCRIBER AND TGID MAY BE DISABLED!!!
#
# The 'action' May be PERMIT|DENY
# Each entry may be a single radio id, or a hypenated range (e.g. 1-2999)
# Format:
# ACL = 'action:id|start-end|,id|start-end,....'
# --for example--
# SUB_ACL: DENY:1,1000-2000,4500-60000,17
#
# ACL Types:
# REG_ACL: peer radio IDs for registration (only used on HBP master systems)
# SUB_ACL: subscriber IDs for end-users
# TGID_TS1_ACL: destination talkgroup IDs on Timeslot 1
# TGID_TS2_ACL: destination talkgroup IDs on Timeslot 2
#
# ACLs may be repeated for individual systems if needed for granularity
# Global ACLs will be processed BEFORE the system level ACLs
# Packets will be matched against all ACLs, GLOBAL first. If a packet 'passes'
# All elements, processing continues. Packets are discarded at the first
# negative match, or 'reject' from an ACL element.
#
# If you do not wish to use ACLs, set them to 'PERMIT:ALL'
# TGID_TS1_ACL in the global stanza is used for OPENBRIDGE systems, since all
# traffic is passed as TS 1 between OpenBridges
[GLOBAL]
PATH: ./
PING_TIME: 5
MAX_MISSED: 3
USE_ACL: True
REG_ACL: PERMIT:ALL
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
# NOT YET WORKING: NETWORK REPORTING CONFIGURATION
# Enabling "REPORT" will configure a socket-based reporting
# system that will send the configuration and other items
# to a another process (local or remote) that may process
# the information for some useful purpose, like a web dashboard.
#
# REPORT - True to enable, False to disable
# REPORT_INTERVAL - Seconds between reports
# REPORT_PORT - TCP port to listen on if "REPORT_NETWORKS" = NETWORK
# REPORT_CLIENTS - comma separated list of IPs you will allow clients
# to connect on. Entering a * will allow all.
#
# ****FOR NOW MUST BE TRUE - USE THE LOOPBACK IF YOU DON'T USE THIS!!!****
[REPORTS]
REPORT: True
REPORT_INTERVAL: 60
REPORT_PORT: 4323
REPORT_CLIENTS: 127.0.0.1
# SYSTEM LOGGER CONFIGURAITON
# This allows the logger to be configured without chaning the individual
# python logger stuff. LOG_FILE should be a complete path/filename for *your*
# system -- use /dev/null for non-file handlers.
# LOG_HANDLERS may be any of the following, please, no spaces in the
# list if you use several:
# null
# console
# console-timed
# file
# file-timed
# syslog
# LOG_LEVEL may be any of the standard syslog logging levels, though
# as of now, DEBUG, INFO, WARNING and CRITICAL are the only ones
# used.
#
[LOGGER]
LOG_FILE: /tmp/gps_data.log
LOG_HANDLERS: console-timed
LOG_LEVEL: DEBUG
LOG_NAME: HBlink3 GPS/Data
# DOWNLOAD AND IMPORT SUBSCRIBER, PEER and TGID ALIASES
# Ok, not the TGID, there's no master list I know of to download
# This is intended as a facility for other applcations built on top of
# HBlink to use, and will NOT be used in HBlink directly.
# STALE_DAYS is the number of days since the last download before we
# download again. Don't be an ass and change this to less than a few days.
[ALIASES]
TRY_DOWNLOAD: True
PATH: ./
PEER_FILE: peer_ids.json
SUBSCRIBER_FILE: subscriber_ids.json
TGID_FILE: talkgroup_ids.json
PEER_URL: https://www.radioid.net/static/rptrs.json
SUBSCRIBER_URL: https://www.radioid.net/static/users.json
STALE_DAYS: 1
#####################################################################
# GPS/Data Application - by KF7EEL
# Configure the settings for the DMR GPS to APRS position application here.
#
# DATA_DMR_ID - This is the DMR ID that users send DMR GPS data.
# CALL_TYPE - group, unit, or both. Group if you want users to send data to a talkgroup,
# unit if you want users to send data as a private call, or both if you want both options.
# USER_APRS_SSID - Default APRS SSID assigned to user APRS positions.
# USER_APRS_COMMENT - Default Comment attached to user APRS positions.
# APRS_LOGIN_CALL, PASSCODE, SERVER, and PORT - Login settings for APRS-IS.
[GPS_DATA]
DATA_DMR_ID: 9099
CALL_TYPE: unit
USER_APRS_SSID: 15
USER_APRS_COMMENT: HBLink3 D-APRS -
# Setting APRS_LOGIN_CALL to N0CALL will cause the gateway to not upload packets to APRS server.
APRS_LOGIN_CALL: N0CALL
APRS_LOGIN_PASSCODE: 12345
APRS_SERVER: rotate.aprs2.net
APRS_PORT: 14580
# The APRS filter below is used for the message received script. See http://www.aprs-is.net/javAPRSFilter.aspx for details
# about APRS filters.
APRS_RECEIVE_LOGIN_CALL: N0CALL-1
APRS_FILTER: r/47/-120/500 t/m
# The following settings are only applicable if you are using the gps_data_beacon_igate script.
# They do not affect the operation gps_data itself.
# Time in minutes.
IGATE_BEACON_TIME = 45
IGATE_BEACON_COMMENT = HBLink3 D-APRS Gateway
IGATE_BEACON_ICON = /I
IGATE_LATITUDE = 0000.00N
IGATE_LONGITUDE = 00000.00W
# User settings file, MUST configure using absolute path.
USER_SETTINGS_FILE: /path/to/user_settings.txt
# The email gateway settingns below are OPTIONAL. They are NOT REQUIRED if you don't want
http://www.aprs-is.net/javAPRSFilter.aspx# to enable the email gateway. Leave as is to disable.
EMAIL_SENDER: test@example.org
EMAIL_PASSWORD: letmein
SMTP_SERVER: smtp.gmail.com
SMTP_PORT: 465
# The options below are required for operation of the dashboard and will cause errors in gps_data.py
# if configured wrong. Leave them as default unless you know what you are doing.
# If you do change, you must use absolute paths.
LOCATION_FILE: /tmp/gps_data_user_loc.txt
BULLETIN_BOARD_FILE: /tmp/gps_data_user_bb.txt
MAILBOX_FILE: /tmp/gps_data_user_mailbox.txt
EMERGENCY_SOS_FILE: /tmp/gps_data_user_sos.txt
# The following options are used for the dashboard. The dashboard is optional.
# Title of the Dashboard
DASHBOARD_TITLE: HBLink3 D-APRS Dashboard
# Logo used on dashboard page
LOGO: https://raw.githubusercontent.com/kf7eel/hblink3/gps/HBlink.png
# Port to run server
DASH_PORT: 8092
# IP to run server on
DASH_HOST: 127.0.0.1
#Description of dashboard to show on main page
DESCRIPTION: Welcome to the dashboard.
# Gateway contact info displayed on about page.
CONTACT_NAME: your name
CONTACT_CALL: N0CALL
CONTACT_EMAIL: email@example.org
CONTACT_WEBSITE: https://hbl.ink
# Time format for display
TIME_FORMAT: %%H:%%M:%%S - %%m/%%d/%%y
# Center dashboard map over these coordinates
MAP_CENTER_LAT: 47.00
MAP_CENTER_LON: -120.00
ZOOM_LEVEL: 7
# List and preview of some map themes at http://leaflet-extras.github.io/leaflet-providers/preview/
# The following are options for map themes and just work, you should use one of these: “OpenStreetMap”, “Stamen” (Terrain, Toner, and Watercolor),
MAP_THEME: Stamen Toner
# RSS feed link, shows in the link section of each RSS item.
RSS_LINK: http://localhost:8092
#####################################################################
# OPENBRIDGE INSTANCES - DUPLICATE SECTION FOR MULTIPLE CONNECTIONS
# OpenBridge is a protocol originall created by DMR+ for connection between an
# IPSC2 server and Brandmeister. It has been implemented here at the suggestion
# of the Brandmeister team as a way to legitimately connect HBlink to the
# Brandemiester network.
# It is recommended to name the system the ID of the Brandmeister server that
# it connects to, but is not necessary. TARGET_IP and TARGET_PORT are of the
# Brandmeister or IPSC2 server you are connecting to. PASSPHRASE is the password
# that must be agreed upon between you and the operator of the server you are
# connecting to. NETWORK_ID is a number in the format of a DMR Radio ID that
# will be sent to the other server to identify this connection.
# other parameters follow the other system types.
#
# ACLs:
# OpenBridge does not 'register', so registration ACL is meaningless.
# Proper OpenBridge passes all traffic on TS1.
# HBlink can extend OPB to use both slots for unit calls only.
# Setting "BOTH_SLOTS" True ONLY affects unit traffic!
# Otherwise ACLs work as described in the global stanza
##[OBP-1]
##MODE: OPENBRIDGE
##ENABLED: True
##IP:
##PORT: 62035
##NETWORK_ID: 3129100
##PASSPHRASE: password
##TARGET_IP: 1.2.3.4
##TARGET_PORT: 62035
##BOTH_SLOTS: True
##USE_ACL: True
##SUB_ACL: DENY:1
##TGID_ACL: PERMIT:ALL
# MASTER INSTANCES - DUPLICATE SECTION FOR MULTIPLE MASTERS
# HomeBrew Protocol Master instances go here.
# IP may be left blank if there's one interface on your system.
# Port should be the port you want this master to listen on. It must be unique
# and unused by anything else.
# Repeat - if True, the master repeats traffic to peers, False, it does nothing.
#
# MAX_PEERS -- maximun number of peers that may be connect to this master
# at any given time. This is very handy if you're allowing hotspots to
# connect, or using a limited computer like a Raspberry Pi.
#
# ACLs:
# See comments in the GLOBAL stanza
[MASTER-1]
MODE: MASTER
ENABLED: False
REPEAT: True
MAX_PEERS: 10
EXPORT_AMBE: False
IP:
PORT: 54000
PASSPHRASE: password
GROUP_HANGTIME: 5
USE_ACL: True
REG_ACL: DENY:1
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
# PEER INSTANCES - DUPLICATE SECTION FOR MULTIPLE PEERS
# There are a LOT of errors in the HB Protocol specifications on this one!
# MOST of these items are just strings and will be properly dealt with by the program
# The TX & RX Frequencies are 9-digit numbers, and are the frequency in Hz.
# Latitude is an 8-digit unsigned floating point number.
# Longitude is a 9-digit signed floating point number.
# Height is in meters
# Setting Loose to True relaxes the validation on packets received from the master.
# This will allow HBlink to connect to a non-compliant system such as XLXD, DMR+ etc.
#
# ACLs:
# See comments in the GLOBAL stanza
[D-APRS]
MODE: PEER
ENABLED: True
LOOSE: True
EXPORT_AMBE: False
IP:
PORT: 54071
MASTER_IP: localhost
MASTER_PORT: 54070
PASSPHRASE: passw0rd
CALLSIGN: D-APRS
RADIO_ID: 9099
RX_FREQ: 000000000
TX_FREQ: 000000000
TX_POWER: 0
COLORCODE: 1
SLOTS: 1
LATITUDE: 00.0000
LONGITUDE: 000.0000
HEIGHT: 0
LOCATION: This Server
DESCRIPTION: GPS to APRS
URL: www.github.com/kf7eel/hblink3
SOFTWARE_ID: 20170620
PACKAGE_ID: MMDVM_HBlink
GROUP_HANGTIME: 5
OPTIONS:
USE_ACL: True
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL

View File

@ -1,820 +0,0 @@
#!/usr/bin/env python3
#
###############################################################################
# HBLink - Copyright (C) 2020 Cortney T. Buffington, N0MJS <n0mjs@me.com>
# GPS/Data - Copyright (C) 2020 Eric Craw, KF7EEL <kf7eel@qsl.net>
# Annotated modifications Copyright (C) 2021 Xavier FRS2013
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
This is a GPS and Data application. It decodes and reassambles DMR GPS packets and
uploads them th APRS-IS.
'''
# Python modules we need
import sys
from bitarray import bitarray
from time import time
from importlib import import_module
from types import ModuleType
# Twisted is pretty important, so I keep it separate
from twisted.internet.protocol import Factory, Protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet import reactor, task
# Things we import from the main hblink module
from hblink import HBSYSTEM, OPENBRIDGE, systems, hblink_handler, reportFactory, REPORT_OPCODES, config_reports, mk_aliases, acl_check
from dmr_utils3.utils import bytes_3, int_id, get_alias
from dmr_utils3 import decode, bptc, const
import config
import log
import const
# The module needs logging logging, but handlers, etc. are controlled by the parent
import logging
logger = logging.getLogger(__name__)
import traceback
# Other modules we need for data and GPS
from bitarray import bitarray
from binascii import b2a_hex as ahex
import re
##from binascii import a2b_hex as bhex
import aprslib
import datetime
from bitarray.util import ba2int as ba2num
from bitarray.util import ba2hex as ba2hx
import codecs
import time
#Needed for working with NMEA
import pynmea2
# Modules for executing commands/scripts
import os
from gps_functions import cmd_list
# Module for maidenhead grids
try:
import maidenhead as mh
except Exception as error_exception:
logger.info('Error importing maidenhead module, make sure it is installed.')
# Module for sending email
try:
import smtplib
except Exception as error_exception:
logger.info('Error importing smtplib module, make sure it is installed.')
#Modules for APRS settings
import ast
from pathlib import Path
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
__author__ = 'Cortney T. Buffington, N0MJS; Eric Craw, KF7EEL'
__copyright__ = 'Copyright (c) 2020 Cortney T. Buffington'
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
__license__ = 'GNU GPLv3'
__maintainer__ = 'Eric Craw, KF7EEL'
__email__ = 'kf7eel@qsl.net'
__status__ = 'pre-alpha'
# Known to work with: AT-D878
# Must have the following at line 1054 in bridge.py to forward group vcsbk, also there is a typo there:
# self.group_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _frame_type, _dtype_vseq, _stream_id, _data)
##################################################################################################
# Headers for GPS by model of radio:
# AT-D878 - Compressed UDP
# MD-380 - Unified Data Transport
hdr_type = ''
btf = -1
ssid = ''
# From dmr_utils3, modified to decode entire packet. Works for 1/2 rate coded data.
def decode_full(_data):
binlc = bitarray(endian='big')
binlc.extend([_data[136],_data[121],_data[106],_data[91], _data[76], _data[61], _data[46], _data[31]])
binlc.extend([_data[152],_data[137],_data[122],_data[107],_data[92], _data[77], _data[62], _data[47], _data[32], _data[17], _data[2] ])
binlc.extend([_data[123],_data[108],_data[93], _data[78], _data[63], _data[48], _data[33], _data[18], _data[3], _data[184],_data[169]])
binlc.extend([_data[94], _data[79], _data[64], _data[49], _data[34], _data[19], _data[4], _data[185],_data[170],_data[155],_data[140]])
binlc.extend([_data[65], _data[50], _data[35], _data[20], _data[5], _data[186],_data[171],_data[156],_data[141],_data[126],_data[111]])
binlc.extend([_data[36], _data[21], _data[6], _data[187],_data[172],_data[157],_data[142],_data[127],_data[112],_data[97], _data[82] ])
binlc.extend([_data[7], _data[188],_data[173],_data[158],_data[143],_data[128],_data[113],_data[98], _data[83]])
#This is the rest of the Full LC data -- the RS1293 FEC that we don't need
# This is extremely important for SMS and GPS though.
binlc.extend([_data[68],_data[53],_data[174],_data[159],_data[144],_data[129],_data[114],_data[99],_data[84],_data[69],_data[54],_data[39]])
binlc.extend([_data[24],_data[145],_data[130],_data[115],_data[100],_data[85],_data[70],_data[55],_data[40],_data[25],_data[10],_data[191]])
return binlc
n_packet_assembly = 0
packet_assembly = ''
final_packet = ''
#Convert DMR packet to binary from MMDVM packet and remove Slot Type and EMB Sync stuff to allow for BPTC 196,96 decoding
def bptc_decode(_data):
binary_packet = bitarray(decode.to_bits(_data[20:]))
del binary_packet[98:166]
return decode_full(binary_packet)
# Placeholder for future header id
def header_ID(_data):
hex_hdr = str(ahex(bptc_decode(_data)))
return hex_hdr[2:6]
# Work in progress, used to determine data format
## pass
def aprs_send(packet):
if aprs_callsign == 'N0CALL':
logger.info('APRS callsighn set to N0CALL, packet not sent.')
pass
else:
AIS = aprslib.IS(aprs_callsign, passwd=aprs_passcode,host=aprs_server, port=aprs_port)
AIS.connect()
AIS.sendall(packet)
AIS.close()
logger.info('Packet sent to APRS-IS.')
# For future use
##def position_timer(aprs_call):
## dash_entries = ast.literal_eval(os.popen('cat ' + loc_file).read())
## for i in dash_entries:
## if aprs_call == i['call']:
## if time.time()
def dashboard_loc_write(call, lat, lon, time, comment):
dash_entries = ast.literal_eval(os.popen('cat /tmp/gps_data_user_loc.txt').read())
dash_entries.insert(0, {'call': call, 'lat': lat, 'lon': lon, 'time':time, 'comment':comment})
# Clear old entries
list_index = 0
call_count = 0
new_dash_entries = []
for i in dash_entries:
if i['call'] == call:
if call_count >= 25:
pass
else:
new_dash_entries.append(i)
call_count = call_count + 1
if call != i['call']:
new_dash_entries.append(i)
pass
list_index = list_index + 1
with open(loc_file, 'w') as user_loc_file:
user_loc_file.write(str(new_dash_entries[:500]))
user_loc_file.close()
logger.info('User location saved for dashboard')
#logger.info(dash_entries)
def dashboard_bb_write(call, dmr_id, time, bulletin):
#try:
dash_bb = ast.literal_eval(os.popen('cat ' + bb_file).read())
# except:
# dash_entries = []
dash_bb.insert(0, {'call': call, 'dmr_id': dmr_id, 'time': time, 'bulletin':bulletin})
with open(bb_file, 'w') as user_bb_file:
user_bb_file.write(str(dash_bb[:20]))
user_bb_file.close()
logger.info('User bulletin entry saved.')
#logger.info(dash_bb)
def mailbox_write(call, dmr_id, time, message, recipient):
#try:
mail_file = ast.literal_eval(os.popen('cat ' + the_mailbox_file).read())
mail_file.insert(0, {'call': call, 'dmr_id': dmr_id, 'time': time, 'message':message, 'recipient': recipient})
with open(the_mailbox_file, 'w') as mailbox_file:
mailbox_file.write(str(mail_file[:100]))
mailbox_file.close()
logger.info('User mail saved.')
def mailbox_delete(dmr_id):
mail_file = ast.literal_eval(os.popen('cat ' + the_mailbox_file).read())
call = str(get_alias((dmr_id), subscriber_ids))
new_data = []
for message in mail_file:
if message['recipient'] != call:
new_data.append(message)
with open(the_mailbox_file, 'w') as mailbox_file:
mailbox_file.write(str(new_data[:100]))
mailbox_file.close()
logger.info('Mailbox updated. Delete occurred.')
def sos_write(dmr_id, time, message):
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
try:
if user_settings[dmr_id][1]['ssid'] == '':
sos_call = user_settings[dmr_id][0]['call'] + '-' + user_ssid
else:
sos_call = user_settings[dmr_id][0]['call'] + '-' + user_settings[dmr_id][1]['ssid']
except:
sos_call = str(get_alias((dmr_id), subscriber_ids))
sos_info = {'call': sos_call, 'dmr_id': dmr_id, 'time': time, 'message':message}
with open(emergency_sos_file, 'w') as sos_file:
sos_file.write(str(sos_info))
sos_file.close()
logger.info('Saved SOS.')
# Send email via SMTP function
def send_email(to_email, email_subject, email_message):
global smtp_server
sender_address = email_sender
account_password = email_password
smtp_server = smtplib.SMTP_SSL(smtp_server, int(smtp_port))
smtp_server.login(sender_address, account_password)
message = "From: " + aprs_callsign + " D-APRS Gateway\nTo: " + to_email + "\nContent-type: text/html\nSubject: " + email_subject + "\n\n" + '<strong>' + email_subject + '</strong><p>&nbsp;</p><h3>' + email_message + '</h3><p>&nbsp;</p><p>This message was sent to you from a D-APRS gateway operated by <strong>' + aprs_callsign + '</strong>. Do not reply as this gateway is only one way at this time.</p>'
smtp_server.sendmail(sender_address, to_email, message)
smtp_server.close()
# Thanks for this forum post for this - https://stackoverflow.com/questions/2579535/convert-dd-decimal-degrees-to-dms-degrees-minutes-seconds-in-python
def decdeg2dms(dd):
is_positive = dd >= 0
dd = abs(dd)
minutes,seconds = divmod(dd*3600,60)
degrees,minutes = divmod(minutes,60)
degrees = degrees if is_positive else -degrees
return (degrees,minutes,seconds)
def user_setting_write(dmr_id, setting, value):
## try:
# Open file and load as dict for modification
with open(user_settings_file, 'r') as f:
## if f.read() == '{}':
## user_dict = {}
user_dict = ast.literal_eval(f.read())
logger.info('Current settings: ' + str(user_dict))
if dmr_id not in user_dict:
user_dict[dmr_id] = [{'call': str(get_alias((dmr_id), subscriber_ids))}, {'ssid': ''}, {'icon': ''}, {'comment': ''}]
if setting.upper() == 'ICON':
user_dict[dmr_id][2]['icon'] = value
if setting.upper() == 'SSID':
user_dict[dmr_id][1]['ssid'] = value
if setting.upper() == 'COM':
user_comment = user_dict[dmr_id][3]['comment'] = value[0:35]
if setting.upper() == 'APRS':
user_dict[dmr_id] = [{'call': str(get_alias((dmr_id), subscriber_ids))}, {'ssid': ''}, {'icon': ''}, {'comment': ''}]
if setting.upper() == 'PIN':
try:
if user_dict[dmr_id]:
user_dict[dmr_id][4]['pin'] = value
if not user_dict[dmr_id]:
user_dict[dmr_id] = [{'call': str(get_alias((dmr_id), subscriber_ids))}, {'ssid': ''}, {'icon': ''}, {'comment': ''}, {'pin': pin}]
except:
user_dict[dmr_id].append({'pin': value})
f.close()
logger.info('Loaded user settings. Preparing to write...')
# Write modified dict to file
with open(user_settings_file, 'w') as user_dict_file:
user_dict_file.write(str(user_dict))
user_dict_file.close()
logger.info('User setting saved')
f.close()
packet_assembly = ''
# Process SMS, do something bases on message
def process_sms(_rf_src, sms):
if sms == 'ID':
logger.info(str(get_alias(int_id(_rf_src), subscriber_ids)) + ' - ' + str(int_id(_rf_src)))
elif sms == 'TEST':
logger.info('It works!')
elif '@ICON' in sms:
user_setting_write(int_id(_rf_src), re.sub(' .*|@','',sms), re.sub('@ICON| ','',sms))
elif '@SSID' in sms:
user_setting_write(int_id(_rf_src), re.sub(' .*|@','',sms), re.sub('@SSID| ','',sms))
elif '@COM' in sms:
user_setting_write(int_id(_rf_src), re.sub(' .*|@','',sms), re.sub('@COM |@COM','',sms))
elif '@PIN' in sms:
user_setting_write(int_id(_rf_src), re.sub(' .*|@','',sms), int(re.sub('@PIN |@PIN','',sms)))
# Write blank entry to cause APRS receive to look for packets for this station.
elif '@APRS' in sms:
user_setting_write(int_id(_rf_src), 'APRS', '')
elif '@BB' in sms:
dashboard_bb_write(get_alias(int_id(_rf_src), subscriber_ids), int_id(_rf_src), time.time(), re.sub('@BB|@BB ','',sms))
elif '@' and ' E-' in sms:
email_message = str(re.sub('.*@|.* E-', '', sms))
to_email = str(re.sub(' E-.*', '', sms))
email_subject = 'New message from ' + str(get_alias(int_id(_rf_src), subscriber_ids))
logger.info('Email to: ' + to_email)
logger.info('Message: ' + email_message)
try:
send_email(to_email, email_subject, email_message)
logger.info('Email sent.')
except Exception as error_exception:
logger.info('Failed to send email.')
logger.info(error_exception)
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
elif '@SOS' in sms or '@NOTICE' in sms:
sos_write(int_id(_rf_src), time.time(), sms)
elif '@REM SOS' == sms:
os.remove(emergency_sos_file)
logger.info('Removing SOS or Notice')
elif '@' and 'M-' in sms:
message = re.sub('^@|.* M-|','',sms)
recipient = re.sub('@| M-.*','',sms)
mailbox_write(get_alias(int_id(_rf_src), subscriber_ids), int_id(_rf_src), time.time(), message, str(recipient).upper())
elif '@REM MAIL' == sms:
mailbox_delete(_rf_src)
elif '@MH' in sms:
grid_square = re.sub('@MH ', '', sms)
if len(grid_square) < 6:
pass
else:
lat = decdeg2dms(mh.to_location(grid_square)[0])
lon = decdeg2dms(mh.to_location(grid_square)[1])
if lon[0] < 0:
lon_dir = 'W'
if lon[0] > 0:
lon_dir = 'E'
if lat[0] < 0:
lat_dir = 'S'
if lat[0] > 0:
lat_dir = 'N'
#logger.info(lat)
#logger.info(lat_dir)
aprs_lat = str(str(re.sub('\..*|-', '', str(lat[0]))) + str(re.sub('\..*', '', str(lat[1])) + '.')).zfill(5) + ' ' + lat_dir
aprs_lon = str(str(re.sub('\..*|-', '', str(lon[0]))) + str(re.sub('\..*', '', str(lon[1])) + '.')).zfill(6) + ' ' + lon_dir
logger.info('Latitude: ' + str(aprs_lat))
logger.info('Longitude: ' + str(aprs_lon))
# 14FRS2013 simplified and moved settings retrieval
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
if int_id(_rf_src) not in user_settings:
ssid = str(user_ssid)
icon_table = '/'
icon_icon = '['
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
else:
if user_settings[int_id(_rf_src)][1]['ssid'] == '':
ssid = user_ssid
if user_settings[int_id(_rf_src)][3]['comment'] == '':
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
if user_settings[int_id(_rf_src)][2]['icon'] == '':
icon_table = '/'
icon_icon = '['
if user_settings[int_id(_rf_src)][2]['icon'] != '':
icon_table = user_settings[int_id(_rf_src)][2]['icon'][0]
icon_icon = user_settings[int_id(_rf_src)][2]['icon'][1]
if user_settings[int_id(_rf_src)][1]['ssid'] != '':
ssid = user_settings[int_id(_rf_src)][1]['ssid']
if user_settings[int_id(_rf_src)][3]['comment'] != '':
comment = user_settings[int_id(_rf_src)][3]['comment']
aprs_loc_packet = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid + '>APHBL3,TCPIP*:@' + str(datetime.datetime.utcnow().strftime("%H%M%Sh")) + str(aprs_lat) + icon_table + str(aprs_lon) + icon_icon + '/' + str(comment)
logger.info(aprs_loc_packet)
logger.info('User comment: ' + comment)
logger.info('User SSID: ' + ssid)
logger.info('User icon: ' + icon_table + icon_icon)
try:
aprslib.parse(aprs_loc_packet)
aprs_send(aprs_loc_packet)
dashboard_loc_write(str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid, aprs_lat, aprs_lon, time.time(), comment)
#logger.info('Sent manual position to APRS')
except Exception as error_exception:
logger.info('Exception. Not uploaded')
logger.info(error_exception)
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
packet_assembly = ''
elif 'A-' in sms and '@' in sms:
#Example SMS text: @ARMDS A-This is a test.
aprs_dest = re.sub('@| A-.*','',sms)
aprs_msg = re.sub('^@|.* A-|','',sms)
logger.info('APRS message to ' + aprs_dest.upper() + '. Message: ' + aprs_msg)
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
if int_id(_rf_src) in user_settings and user_settings[int_id(_rf_src)][1]['ssid'] != '':
ssid = user_settings[int_id(_rf_src)][1]['ssid']
else:
ssid = user_ssid
aprs_msg_pkt = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + str(ssid) + '>APHBL3,TCPIP*::' + str(aprs_dest).ljust(9).upper() + ':' + aprs_msg[0:73]
logger.info(aprs_msg_pkt)
try:
aprslib.parse(aprs_msg_pkt)
aprs_send(aprs_msg_pkt)
#logger.info('Packet sent.')
except Exception as error_exception:
logger.info('Error uploading MSG packet.')
logger.info(error_exception)
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
try:
if sms in cmd_list:
logger.info('Executing command/script.')
os.popen(cmd_list[sms]).read()
packet_assembly = ''
except Exception as error_exception:
logger.info('Exception. Command possibly not in list, or other error.')
packet_assembly = ''
logger.info(error_exception)
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
else:
pass
###########
class DATA_SYSTEM(HBSYSTEM):
## global n_packet_assembly, packet_assembly
def __init__(self, _name, _config, _report):
HBSYSTEM.__init__(self, _name, _config, _report)
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
# Capture data headers
global n_packet_assembly, hdr_type
#logger.info(_dtype_vseq)
logger.info(time.strftime('%H:%M:%S - %m/%d/%y'))
#logger.info('Special debug for developement:')
#logger.info(ahex(bptc_decode(_data)))
#logger.info(hdr_type)
#logger.info((ba2num(bptc_decode(_data)[8:12])))
if int_id(_dst_id) == data_id:
#logger.info(type(_seq))
if type(_seq) is bytes:
pckt_seq = int.from_bytes(_seq, 'big')
else:
pckt_seq = _seq
# Try to classify header
# UDT header has DPF of 0101, which is 5.
# If 5 is at position 3, then this should be a UDT header for MD-380 type radios.
# Coordinates are usually in the very next block after the header, we will discard the rest.
#logger.info(ahex(bptc_decode(_data)[0:10]))
if _call_type == call_type and header_ID(_data)[3] == '5' and ba2num(bptc_decode(_data)[69:72]) == 0 and ba2num(bptc_decode(_data)[8:12]) == 0 or (_call_type == 'vcsbk' and header_ID(_data)[3] == '5' and ba2num(bptc_decode(_data)[69:72]) == 0 and ba2num(bptc_decode(_data)[8:12]) == 0):
global udt_block
logger.info('MD-380 type UDT header detected. Very next packet should be location.')
hdr_type = '380'
if _dtype_vseq == 6 and hdr_type == '380' or _dtype_vseq == 'group' and hdr_type == '380':
udt_block = 1
if _dtype_vseq == 7 and hdr_type == '380':
udt_block = udt_block - 1
if udt_block == 0:
logger.info('MD-380 type packet. This should contain the GPS location.')
logger.info('Packet: ' + str(ahex(bptc_decode(_data))))
if ba2num(bptc_decode(_data)[1:2]) == 1:
lat_dir = 'N'
if ba2num(bptc_decode(_data)[1:2]) == 0:
lat_dir = 'S'
if ba2num(bptc_decode(_data)[2:3]) == 1:
lon_dir = 'E'
if ba2num(bptc_decode(_data)[2:3]) == 0:
lon_dir = 'W'
lat_deg = ba2num(bptc_decode(_data)[11:18])
lon_deg = ba2num(bptc_decode(_data)[38:46])
lat_min = ba2num(bptc_decode(_data)[18:24])
lon_min = ba2num(bptc_decode(_data)[46:52])
lat_min_dec = str(ba2num(bptc_decode(_data)[24:38])).zfill(4)
lon_min_dec = str(ba2num(bptc_decode(_data)[52:66])).zfill(4)
# Old MD-380 coordinate format, keep here until new is confirmed working.
#aprs_lat = str(str(lat_deg) + str(lat_min) + '.' + str(lat_min_dec)[0:2]).zfill(7) + lat_dir
#aprs_lon = str(str(lon_deg) + str(lon_min) + '.' + str(lon_min_dec)[0:2]).zfill(8) + lon_dir
# Fix for MD-380 by G7HIF
aprs_lat = str(str(lat_deg) + str(lat_min).zfill(2) + '.' + str(lat_min_dec)[0:2]).zfill(7) + lat_dir
aprs_lon = str(str(lon_deg) + str(lon_min).zfill(2) + '.' + str(lon_min_dec)[0:2]).zfill(8) + lon_dir
# Form APRS packet
#logger.info(aprs_loc_packet)
logger.info('Lat: ' + str(aprs_lat) + ' Lon: ' + str(aprs_lon))
# 14FRS2013 simplified and moved settings retrieval
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
if int_id(_rf_src) not in user_settings:
ssid = str(user_ssid)
icon_table = '/'
icon_icon = '['
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
else:
if user_settings[int_id(_rf_src)][1]['ssid'] == '':
ssid = user_ssid
if user_settings[int_id(_rf_src)][3]['comment'] == '':
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
if user_settings[int_id(_rf_src)][2]['icon'] == '':
icon_table = '/'
icon_icon = '['
if user_settings[int_id(_rf_src)][2]['icon'] != '':
icon_table = user_settings[int_id(_rf_src)][2]['icon'][0]
icon_icon = user_settings[int_id(_rf_src)][2]['icon'][1]
if user_settings[int_id(_rf_src)][1]['ssid'] != '':
ssid = user_settings[int_id(_rf_src)][1]['ssid']
if user_settings[int_id(_rf_src)][3]['comment'] != '':
comment = user_settings[int_id(_rf_src)][3]['comment']
aprs_loc_packet = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid + '>APHBL3,TCPIP*:@' + str(datetime.datetime.utcnow().strftime("%H%M%Sh")) + str(aprs_lat) + icon_table + str(aprs_lon) + icon_icon + '/' + str(comment)
logger.info(aprs_loc_packet)
logger.info('User comment: ' + comment)
logger.info('User SSID: ' + ssid)
logger.info('User icon: ' + icon_table + icon_icon)
# Attempt to prevent malformed packets from being uploaded.
try:
aprslib.parse(aprs_loc_packet)
float(lat_deg) < 91
float(lon_deg) < 121
aprs_send(aprs_loc_packet)
dashboard_loc_write(str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid, aprs_lat, aprs_lon, time.time(), comment)
#logger.info('Sent APRS packet')
except Exception as error_exception:
logger.info('Error. Failed to send packet. Packet may be malformed.')
logger.info(error_exception)
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
udt_block = 1
hdr_type = ''
else:
pass
#NMEA type packets for Anytone like radios.
#if _call_type == call_type or (_call_type == 'vcsbk' and pckt_seq > 3): #int.from_bytes(_seq, 'big') > 3 ):
# 14FRS2013 contributed improved header filtering, KF7EEL added conditions to allow both call types at the same time
if _call_type == call_type or (_call_type == 'vcsbk' and pckt_seq > 3 and call_type != 'unit') or (_call_type == 'group' and pckt_seq > 3 and call_type != 'unit') or (_call_type == 'group' and pckt_seq > 3 and call_type == 'both') or (_call_type == 'vcsbk' and pckt_seq > 3 and call_type == 'both') or (_call_type == 'unit' and pckt_seq > 3 and call_type == 'both'): #int.from_bytes(_seq, 'big') > 3 ):
global packet_assembly, btf
if _dtype_vseq == 6 or _dtype_vseq == 'group':
global btf, hdr_start
hdr_start = str(header_ID(_data))
logger.info('Header from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + '. DMR ID: ' + str(int_id(_rf_src)))
logger.info(ahex(bptc_decode(_data)))
logger.info('Blocks to follow: ' + str(ba2num(bptc_decode(_data)[65:72])))
btf = ba2num(bptc_decode(_data)[65:72])
# Try resetting packet_assembly
packet_assembly = ''
# Data blocks at 1/2 rate, see https://github.com/g4klx/MMDVM/blob/master/DMRDefines.h for data types. _dtype_seq defined here also
if _dtype_vseq == 7:
btf = btf - 1
logger.info('Block #: ' + str(btf))
#logger.info(_seq)
logger.info('Data block from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + '. DMR ID: ' + str(int_id(_rf_src)))
logger.info(ahex(bptc_decode(_data)))
if _seq == 0:
n_packet_assembly = 0
packet_assembly = ''
#if btf < btf + 1:
# 14FRS2013 removed condition, works great!
n_packet_assembly = n_packet_assembly + 1
packet_assembly = packet_assembly + str(bptc_decode(_data)) #str((decode_full_lc(b_packet)).strip('bitarray('))
# Use block 0 as trigger. $GPRMC must also be in string to indicate NMEA.
# This triggers the APRS upload
if btf == 0:
final_packet = str(bitarray(re.sub("\)|\(|bitarray|'", '', packet_assembly)).tobytes().decode('utf-8', 'ignore'))
sms_hex = str(ba2hx(bitarray(re.sub("\)|\(|bitarray|'", '', packet_assembly))))
sms_hex_string = re.sub("b'|'", '', str(sms_hex))
#NMEA GPS sentence
if '$GPRMC' in final_packet or '$GNRMC' in final_packet:
logger.info(final_packet + '\n')
# Eliminate excess bytes based on NMEA type
# GPRMC
if 'GPRMC' in final_packet:
logger.info('GPRMC location')
#nmea_parse = re.sub('A\*.*|.*\$', '', str(final_packet))
nmea_parse = re.sub('A\*.*|.*\$|\n.*', '', str(final_packet))
# GNRMC
if 'GNRMC' in final_packet:
logger.info('GNRMC location')
nmea_parse = re.sub('.*\$|\n.*|V\*.*', '', final_packet)
loc = pynmea2.parse(nmea_parse, check=False)
logger.info('Latitude: ' + str(loc.lat) + str(loc.lat_dir) + ' Longitude: ' + str(loc.lon) + str(loc.lon_dir) + ' Direction: ' + str(loc.true_course) + ' Speed: ' + str(loc.spd_over_grnd) + '\n')
try:
# Begin APRS format and upload
# Disable opening file for reading to reduce "collision" or reading and writing at same time.
# 14FRS2013 simplified and moved settings retrieval
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
if int_id(_rf_src) not in user_settings:
ssid = str(user_ssid)
icon_table = '/'
icon_icon = '['
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
else:
if user_settings[int_id(_rf_src)][1]['ssid'] == '':
ssid = user_ssid
if user_settings[int_id(_rf_src)][3]['comment'] == '':
comment = aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
if user_settings[int_id(_rf_src)][2]['icon'] == '':
icon_table = '/'
icon_icon = '['
if user_settings[int_id(_rf_src)][2]['icon'] != '':
icon_table = user_settings[int_id(_rf_src)][2]['icon'][0]
icon_icon = user_settings[int_id(_rf_src)][2]['icon'][1]
if user_settings[int_id(_rf_src)][1]['ssid'] != '':
ssid = user_settings[int_id(_rf_src)][1]['ssid']
if user_settings[int_id(_rf_src)][3]['comment'] != '':
comment = user_settings[int_id(_rf_src)][3]['comment']
aprs_loc_packet = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid + '>APHBL3,TCPIP*:@' + str(datetime.datetime.utcnow().strftime("%H%M%Sh")) + str(loc.lat[0:7]) + str(loc.lat_dir) + icon_table + str(loc.lon[0:8]) + str(loc.lon_dir) + icon_icon + str(round(loc.true_course)).zfill(3) + '/' + str(round(loc.spd_over_grnd)).zfill(3) + '/' + str(comment)
logger.info(aprs_loc_packet)
logger.info('User comment: ' + comment)
logger.info('User SSID: ' + ssid)
logger.info('User icon: ' + icon_table + icon_icon)
except Exception as error_exception:
logger.info('Error or user settings file not found, proceeding with default settings.')
aprs_loc_packet = str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + str(user_ssid) + '>APHBL3,TCPIP*:@' + str(datetime.datetime.utcnow().strftime("%H%M%Sh")) + str(loc.lat[0:7]) + str(loc.lat_dir) + '/' + str(loc.lon[0:8]) + str(loc.lon_dir) + '[' + str(round(loc.true_course)).zfill(3) + '/' + str(round(loc.spd_over_grnd)).zfill(3) + '/' + aprs_comment + ' DMR ID: ' + str(int_id(_rf_src))
logger.info(error_exception)
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
try:
# Try parse of APRS packet. If it fails, it will not upload to APRS-IS
aprslib.parse(aprs_loc_packet)
# Float values of lat and lon. Anything that is not a number will cause it to fail.
float(loc.lat)
float(loc.lon)
aprs_send(aprs_loc_packet)
dashboard_loc_write(str(get_alias(int_id(_rf_src), subscriber_ids)) + '-' + ssid, str(loc.lat[0:7]) + str(loc.lat_dir), str(loc.lon[0:8]) + str(loc.lon_dir), time.time(), comment)
except Exception as error_exception:
logger.info('Failed to parse packet. Packet may be deformed. Not uploaded.')
logger.info(error_exception)
logger.info(str(traceback.extract_tb(error_exception.__traceback__)))
#final_packet = ''
# Get callsign based on DMR ID
# End APRS-IS upload
# Assume this is an SMS message
elif '$GPRMC' not in final_packet or '$GNRMC' not in final_packet:
#### # Motorola type SMS header
## if '824a' in hdr_start or '024a' in hdr_start:
## logger.info('\nMotorola type SMS')
## sms = codecs.decode(bytes.fromhex(''.join(sms_hex[74:-8].split('00'))), 'utf-8')
## logger.info('\n\n' + 'Received SMS from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + ', DMR ID: ' + str(int_id(_rf_src)) + ': ' + str(sms) + '\n')
## process_sms(_rf_src, sms)
## packet_assembly = ''
## # ETSI? type SMS header
## elif '0244' in hdr_start or '8244' in hdr_start:
## logger.info('ETSI? type SMS')
## sms = codecs.decode(bytes.fromhex(''.join(sms_hex[64:-8].split('00'))), 'utf-8')
## logger.info('\n\n' + 'Received SMS from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + ', DMR ID: ' + str(int_id(_rf_src)) + ': ' + str(sms) + '\n')
## #logger.info(final_packet)
## #logger.info(sms_hex[64:-8])
## process_sms(_rf_src, sms)
## packet_assembly = ''
####
## else:
logger.info('\nSMS detected. Attempting to parse.')
#logger.info(final_packet)
logger.info(sms_hex)
## logger.info(type(sms_hex))
logger.info('Attempting to find command...')
## sms = codecs.decode(bytes.fromhex(''.join(sms_hex[:-8].split('00'))), 'utf-8', 'ignore')
sms = codecs.decode(bytes.fromhex(''.join(sms_hex_string[:-8].split('00'))), 'utf-8', 'ignore')
msg_found = re.sub('.*\n', '', sms)
logger.info('\n\n' + 'Received SMS from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + ', DMR ID: ' + str(int_id(_rf_src)) + ': ' + str(msg_found) + '\n')
process_sms(_rf_src, msg_found)
#packet_assembly = ''
pass
#logger.info(bitarray(re.sub("\)|\(|bitarray|'", '', str(bptc_decode(_data)).tobytes().decode('utf-8', 'ignore'))))
#logger.info('\n\n' + 'Received SMS from ' + str(get_alias(int_id(_rf_src), subscriber_ids)) + ', DMR ID: ' + str(int_id(_rf_src)) + ': ' + str(sms) + '\n')
# Reset the packet assembly to prevent old data from returning.
# 14FRS2013 moved variable reset
hdr_start = ''
n_packet_assembly = 0
packet_assembly = ''
btf = 0
#logger.info(_seq)
#packet_assembly = '' #logger.info(_dtype_vseq)
#logger.info(ahex(bptc_decode(_data)).decode('utf-8', 'ignore'))
#logger.info(bitarray(re.sub("\)|\(|bitarray|'", '', str(bptc_decode(_data)).tobytes().decode('utf-8', 'ignore'))))
else:
pass
#************************************************
# MAIN PROGRAM LOOP STARTS HERE
#************************************************
if __name__ == '__main__':
#global aprs_callsign, aprs_passcode, aprs_server, aprs_port, user_ssid, aprs_comment, call_type, data_id
import argparse
import sys
import os
import signal
from dmr_utils3.utils import try_download, mk_id_dict
# Change the current directory to the location of the application
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually gps_data.cfg)')
parser.add_argument('-l', '--logging', action='store', dest='LOG_LEVEL', help='Override config file logging level.')
cli_args = parser.parse_args()
# Ensure we have a path for the config file, if one wasn't specified, then use the default (top of file)
if not cli_args.CONFIG_FILE:
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/gps_data.cfg'
# Call the external routine to build the configuration dictionary
CONFIG = config.build_config(cli_args.CONFIG_FILE)
data_id = int(CONFIG['GPS_DATA']['DATA_DMR_ID'])
# Group call or Unit (private) call
call_type = CONFIG['GPS_DATA']['CALL_TYPE']
# APRS-IS login information
aprs_callsign = CONFIG['GPS_DATA']['APRS_LOGIN_CALL']
aprs_passcode = int(CONFIG['GPS_DATA']['APRS_LOGIN_PASSCODE'])
aprs_server = CONFIG['GPS_DATA']['APRS_SERVER']
aprs_port = int(CONFIG['GPS_DATA']['APRS_PORT'])
user_ssid = CONFIG['GPS_DATA']['USER_APRS_SSID']
aprs_comment = CONFIG['GPS_DATA']['USER_APRS_COMMENT']
# EMAIL variables
email_sender = CONFIG['GPS_DATA']['EMAIL_SENDER']
email_password = CONFIG['GPS_DATA']['EMAIL_PASSWORD']
smtp_server = CONFIG['GPS_DATA']['SMTP_SERVER']
smtp_port = CONFIG['GPS_DATA']['SMTP_PORT']
# Dashboard files
bb_file = CONFIG['GPS_DATA']['BULLETIN_BOARD_FILE']
loc_file = CONFIG['GPS_DATA']['LOCATION_FILE']
the_mailbox_file = CONFIG['GPS_DATA']['MAILBOX_FILE']
emergency_sos_file = CONFIG['GPS_DATA']['EMERGENCY_SOS_FILE']
# User APRS settings
user_settings_file = CONFIG['GPS_DATA']['USER_SETTINGS_FILE']
# Check if user_settings (for APRS settings of users) exists. Creat it if not.
if Path(user_settings_file).is_file():
pass
else:
Path(user_settings_file).touch()
with open(user_settings_file, 'w') as user_dict_file:
user_dict_file.write("{1: [{'call': 'N0CALL'}, {'ssid': ''}, {'icon': ''}, {'comment': ''}]}")
user_dict_file.close()
# Check to see if dashboard files exist
if Path(loc_file).is_file():
pass
else:
Path(loc_file).touch()
with open(loc_file, 'w') as user_loc_file:
user_loc_file.write("[]")
user_loc_file.close()
if Path(bb_file).is_file():
pass
else:
Path(bb_file).touch()
with open(bb_file, 'w') as user_bb_file:
user_bb_file.write("[]")
user_bb_file.close()
if Path(the_mailbox_file).is_file():
pass
else:
Path(the_mailbox_file).touch()
with open(the_mailbox_file, 'w') as user_mail_file:
user_mail_file.write("[]")
user_mail_file.close()
# Start the system logger
if cli_args.LOG_LEVEL:
CONFIG['LOGGER']['LOG_LEVEL'] = cli_args.LOG_LEVEL
logger = log.config_logging(CONFIG['LOGGER'])
logger.info('\n\nCopyright (c) 2013, 2014, 2015, 2016, 2018, 2019\n\tThe Regents of the K0USY Group. All rights reserved.\n GPS and Data decoding by Eric, KF7EEL')
logger.debug('Logging system started, anything from here on gets logged')
# Set up the signal handler
def sig_handler(_signal, _frame):
logger.info('SHUTDOWN: >>>GPS and Data Decoder<<< IS TERMINATING WITH SIGNAL %s', str(_signal))
hblink_handler(_signal, _frame)
logger.info('SHUTDOWN: ALL SYSTEM HANDLERS EXECUTED - STOPPING REACTOR')
reactor.stop()
# Set signal handers so that we can gracefully exit if need be
for sig in [signal.SIGTERM, signal.SIGINT]:
signal.signal(sig, sig_handler)
# Create the name-number mapping dictionaries
peer_ids, subscriber_ids, talkgroup_ids = mk_aliases(CONFIG)
# INITIALIZE THE REPORTING LOOP
if CONFIG['REPORTS']['REPORT']:
report_server = config_reports(CONFIG, reportFactory)
else:
report_server = None
logger.info('(REPORT) TCP Socket reporting not configured')
# HBlink instance creation
logger.info('HBlink \'gps_data.py\' -- SYSTEM STARTING...')
for system in CONFIG['SYSTEMS']:
if CONFIG['SYSTEMS'][system]['ENABLED']:
if CONFIG['SYSTEMS'][system]['MODE'] == 'OPENBRIDGE':
systems[system] = OPENBRIDGE(system, CONFIG, report_server)
else:
systems[system] = DATA_SYSTEM(system, CONFIG, report_server)
reactor.listenUDP(CONFIG['SYSTEMS'][system]['PORT'], systems[system], interface=CONFIG['SYSTEMS'][system]['IP'])
logger.debug('%s instance created: %s, %s', CONFIG['SYSTEMS'][system]['MODE'], system, systems[system])
reactor.run()
# John 3:16 - For God so loved the world, that he gave his only Son,
# that whoever believes in him should not perish but have eternal life.

View File

@ -1,60 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# HBLink - Copyright (C) 2020 Cortney T. Buffington, N0MJS <n0mjs@me.com>
# GPS/Data - Copyright (C) 2020 Eric Craw, KF7EEL <kf7eel@qsl.net>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
This script uploads a beacon to APRS-IS for the GPS/Data Application itself, cuasing it to appear as an igate
an aprs.fi.
'''
import aprslib
import argparse
import os
import config
import time
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually gps_data.cfg)')
cli_args = parser.parse_args()
if not cli_args.CONFIG_FILE:
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/gps_data.cfg'
CONFIG = config.build_config(cli_args.CONFIG_FILE)
print('''
GPS/Data Application Beacon Script by Eric, KF7EEL. https://github.com/kf7eel/hblink3 \n
This script will upload an APRS position for the GPS/Data Application. This usually causes most APRS-IS clients to see the GPS/Data Application
as an i-gate. \n
Using the following setting to upload beacon.\n
Callsign: ''' + CONFIG['GPS_DATA']['APRS_LOGIN_CALL'] + ''' - Position comment: ''' + CONFIG['GPS_DATA']['IGATE_BEACON_COMMENT'] + '''
Beacon time: ''' + CONFIG['GPS_DATA']['IGATE_BEACON_TIME'] + '''
''')
beacon_packet = CONFIG['GPS_DATA']['APRS_LOGIN_CALL'] + '>APHBL3,TCPIP*:!' + CONFIG['GPS_DATA']['IGATE_LATITUDE'] + str(CONFIG['GPS_DATA']['IGATE_BEACON_ICON'][0]) + CONFIG['GPS_DATA']['IGATE_LONGITUDE'] + str(CONFIG['GPS_DATA']['IGATE_BEACON_ICON'][1]) + '/' + CONFIG['GPS_DATA']['IGATE_BEACON_COMMENT']
#print(beacon_packet)
AIS = aprslib.IS(CONFIG['GPS_DATA']['APRS_LOGIN_CALL'], passwd=CONFIG['GPS_DATA']['APRS_LOGIN_PASSCODE'],host=CONFIG['GPS_DATA']['APRS_SERVER'], port=CONFIG['GPS_DATA']['APRS_PORT'])
while int(CONFIG['GPS_DATA']['IGATE_BEACON_TIME']) > 15:
AIS.connect()
AIS.sendall(beacon_packet)
print(beacon_packet)
AIS.close()
time.sleep(int(CONFIG['GPS_DATA']['IGATE_BEACON_TIME'])*60)

View File

@ -1,11 +0,0 @@
# Various configurable options used in the GPS/Data application.
# SMS message that triggers command
cmd_list = {
'COMMAND' : 'echo "command to execute"',
'UPTIME' : 'uptime'
}

View File

@ -1,292 +0,0 @@
# PROGRAM-WIDE PARAMETERS GO HERE
# PATH - working path for files, leave it alone unless you NEED to change it
# PING_TIME - the interval that peers will ping the master, and re-try registraion
# - how often the Master maintenance loop runs
# MAX_MISSED - how many pings are missed before we give up and re-register
# - number of times the master maintenance loop runs before de-registering a peer
#
# ACLs:
#
# Access Control Lists are a very powerful tool for administering your system.
# But they consume packet processing time. Disable them if you are not using them.
# But be aware that, as of now, the configuration stanzas still need the ACL
# sections configured even if you're not using them.
#
# REGISTRATION ACLS ARE ALWAYS USED, ONLY SUBSCRIBER AND TGID MAY BE DISABLED!!!
#
# The 'action' May be PERMIT|DENY
# Each entry may be a single radio id, or a hypenated range (e.g. 1-2999)
# Format:
# ACL = 'action:id|start-end|,id|start-end,....'
# --for example--
# SUB_ACL: DENY:1,1000-2000,4500-60000,17
#
# ACL Types:
# REG_ACL: peer radio IDs for registration (only used on HBP master systems)
# SUB_ACL: subscriber IDs for end-users
# TGID_TS1_ACL: destination talkgroup IDs on Timeslot 1
# TGID_TS2_ACL: destination talkgroup IDs on Timeslot 2
#
# ACLs may be repeated for individual systems if needed for granularity
# Global ACLs will be processed BEFORE the system level ACLs
# Packets will be matched against all ACLs, GLOBAL first. If a packet 'passes'
# All elements, processing continues. Packets are discarded at the first
# negative match, or 'reject' from an ACL element.
#
# If you do not wish to use ACLs, set them to 'PERMIT:ALL'
# TGID_TS1_ACL in the global stanza is used for OPENBRIDGE systems, since all
# traffic is passed as TS 1 between OpenBridges
[GLOBAL]
PATH: ./
PING_TIME: 5
MAX_MISSED: 3
USE_ACL: True
REG_ACL: PERMIT:ALL
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
# NOT YET WORKING: NETWORK REPORTING CONFIGURATION
# Enabling "REPORT" will configure a socket-based reporting
# system that will send the configuration and other items
# to a another process (local or remote) that may process
# the information for some useful purpose, like a web dashboard.
#
# REPORT - True to enable, False to disable
# REPORT_INTERVAL - Seconds between reports
# REPORT_PORT - TCP port to listen on if "REPORT_NETWORKS" = NETWORK
# REPORT_CLIENTS - comma separated list of IPs you will allow clients
# to connect on. Entering a * will allow all.
#
# ****FOR NOW MUST BE TRUE - USE THE LOOPBACK IF YOU DON'T USE THIS!!!****
[REPORTS]
REPORT: True
REPORT_INTERVAL: 60
REPORT_PORT: 4321
REPORT_CLIENTS: 127.0.0.1
# SYSTEM LOGGER CONFIGURAITON
# This allows the logger to be configured without chaning the individual
# python logger stuff. LOG_FILE should be a complete path/filename for *your*
# system -- use /dev/null for non-file handlers.
# LOG_HANDLERS may be any of the following, please, no spaces in the
# list if you use several:
# null
# console
# console-timed
# file
# file-timed
# syslog
# LOG_LEVEL may be any of the standard syslog logging levels, though
# as of now, DEBUG, INFO, WARNING and CRITICAL are the only ones
# used.
#
[LOGGER]
LOG_FILE: /tmp/hblink.log
LOG_HANDLERS: console-timed
LOG_LEVEL: DEBUG
LOG_NAME: HBlink
# DOWNLOAD AND IMPORT SUBSCRIBER, PEER and TGID ALIASES
# Ok, not the TGID, there's no master list I know of to download
# This is intended as a facility for other applcations built on top of
# HBlink to use, and will NOT be used in HBlink directly.
# STALE_DAYS is the number of days since the last download before we
# download again. Don't be an ass and change this to less than a few days.
[ALIASES]
TRY_DOWNLOAD: True
PATH: ./
PEER_FILE: peer_ids.json
SUBSCRIBER_FILE: subscriber_ids.json
TGID_FILE: talkgroup_ids.json
PEER_URL: https://www.radioid.net/static/rptrs.json
SUBSCRIBER_URL: https://www.radioid.net/static/users.json
STALE_DAYS: 7
# OPENBRIDGE INSTANCES - DUPLICATE SECTION FOR MULTIPLE CONNECTIONS
# OpenBridge is a protocol originall created by DMR+ for connection between an
# IPSC2 server and Brandmeister. It has been implemented here at the suggestion
# of the Brandmeister team as a way to legitimately connect HBlink to the
# Brandemiester network.
# It is recommended to name the system the ID of the Brandmeister server that
# it connects to, but is not necessary. TARGET_IP and TARGET_PORT are of the
# Brandmeister or IPSC2 server you are connecting to. PASSPHRASE is the password
# that must be agreed upon between you and the operator of the server you are
# connecting to. NETWORK_ID is a number in the format of a DMR Radio ID that
# will be sent to the other server to identify this connection.
# other parameters follow the other system types.
#
# ACLs:
# OpenBridge does not 'register', so registration ACL is meaningless.
# Proper OpenBridge passes all traffic on TS1.
# HBlink can extend OPB to use both slots for unit calls only.
# Setting "BOTH_SLOTS" True ONLY affects unit traffic!
# Otherwise ACLs work as described in the global stanza
[OBP-1]
MODE: OPENBRIDGE
ENABLED: False
IP:
PORT: 62035
NETWORK_ID: 3129100
PASSPHRASE: password
TARGET_IP: 1.2.3.4
TARGET_PORT: 62035
BOTH_SLOTS: True
USE_ACL: True
SUB_ACL: DENY:1
TGID_ACL: PERMIT:ALL
# MASTER INSTANCES - DUPLICATE SECTION FOR MULTIPLE MASTERS
# HomeBrew Protocol Master instances go here.
# IP may be left blank if there's one interface on your system.
# Port should be the port you want this master to listen on. It must be unique
# and unused by anything else.
# Repeat - if True, the master repeats traffic to peers, False, it does nothing.
#
# MAX_PEERS -- maximun number of peers that may be connect to this master
# at any given time. This is very handy if you're allowing hotspots to
# connect, or using a limited computer like a Raspberry Pi.
#
# ACLs:
# See comments in the GLOBAL stanza
[MASTER-1]
MODE: MASTER
ENABLED: True
REPEAT: True
MAX_PEERS: 10
EXPORT_AMBE: False
IP:
PORT: 54000
PASSPHRASE: s3cr37w0rd
GROUP_HANGTIME: 5
USE_ACL: True
REG_ACL: DENY:1
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
[D-APRS]
MODE: MASTER
ENABLED: True
REPEAT: True
MAX_PEERS: 2
EXPORT_AMBE: False
IP:
PORT: 54070
PASSPHRASE: passw0rd
GROUP_HANGTIME: 5
USE_ACL: True
REG_ACL: DENY:1
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
# PEER INSTANCES - DUPLICATE SECTION FOR MULTIPLE PEERS
# There are a LOT of errors in the HB Protocol specifications on this one!
# MOST of these items are just strings and will be properly dealt with by the program
# The TX & RX Frequencies are 9-digit numbers, and are the frequency in Hz.
# Latitude is an 8-digit unsigned floating point number.
# Longitude is a 9-digit signed floating point number.
# Height is in meters
# Setting Loose to True relaxes the validation on packets received from the master.
# This will allow HBlink to connect to a non-compliant system such as XLXD, DMR+ etc.
#
# ACLs:
# See comments in the GLOBAL stanza
[REPEATER-1]
MODE: PEER
ENABLED: False
LOOSE: False
EXPORT_AMBE: False
IP:
PORT: 54001
MASTER_IP: 172.16.1.1
MASTER_PORT: 54000
PASSPHRASE: homebrew
CALLSIGN: W1ABC
RADIO_ID: 312000
RX_FREQ: 449000000
TX_FREQ: 444000000
TX_POWER: 25
COLORCODE: 1
SLOTS: 1
LATITUDE: 38.0000
LONGITUDE: -095.0000
HEIGHT: 75
LOCATION: Anywhere, USA
DESCRIPTION: This is a cool repeater
URL: www.w1abc.org
SOFTWARE_ID: 20170620
PACKAGE_ID: MMDVM_HBlink
GROUP_HANGTIME: 5
OPTIONS:
USE_ACL: True
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
[ECHO]
MODE: PEER
ENABLED: True
LOOSE: False
EXPORT_AMBE: False
IP:
PORT: 54073
MASTER_IP: localhost
MASTER_PORT: 54072
passphrase: passw0rd
CALLSIGN: ECHO
RADIO_ID: 9999
RX_FREQ: 000000000
TX_FREQ: 000000000
TX_POWER: 0
COLORCODE: 1
SLOTS: 1
LATITUDE: 00.0000
LONGITUDE: 000.0000
HEIGHT: 0
LOCATION: This Server
DESCRIPTION: Echo Server
URL: www.github.com/kf7eel/hblink3
SOFTWARE_ID: 20170620
PACKAGE_ID: MMDVM_HBlink
GROUP_HANGTIME: 5
OPTIONS:
USE_ACL: True
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
[XLX-1]
MODE: XLXPEER
ENABLED: False
LOOSE: True
EXPORT_AMBE: False
IP:
PORT: 54002
MASTER_IP: 172.16.1.1
MASTER_PORT: 62030
PASSPHRASE: passw0rd
CALLSIGN: W1ABC
RADIO_ID: 312000
RX_FREQ: 449000000
TX_FREQ: 444000000
TX_POWER: 25
COLORCODE: 1
SLOTS: 1
LATITUDE: 38.0000
LONGITUDE: -095.0000
HEIGHT: 75
LOCATION: Anywhere, USA
DESCRIPTION: This is a cool repeater
URL: www.w1abc.org
SOFTWARE_ID: 20170620
PACKAGE_ID: MMDVM_HBlink
GROUP_HANGTIME: 5
XLXMODULE: 4004
USE_ACL: True
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL

839
hblink.py
View File

@ -1,839 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
This program does very little on its own. It is intended to be used as a module
to build applications on top of the HomeBrew Repeater Protocol. By itself, it
will only act as a peer or master for the systems specified in its configuration
file (usually hblink.cfg). It is ALWAYS best practice to ensure that this program
works stand-alone before troubleshooting any applications that use it. It has
sufficient logging to be used standalone as a troubleshooting application.
'''
# Specifig functions from modules we need
from binascii import b2a_hex as ahex
from binascii import a2b_hex as bhex
from random import randint
from hashlib import sha256, sha1
from hmac import new as hmac_new, compare_digest
from time import time
from collections import deque
# Twisted is pretty important, so I keep it separate
from twisted.internet.protocol import DatagramProtocol, Factory, Protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet import reactor, task
# Other files we pull from -- this is mostly for readability and segmentation
import log
import config
from const import *
from dmr_utils3.utils import int_id, bytes_4, try_download, mk_id_dict
# Imports for the reporting server
import pickle
from reporting_const import *
# The module needs logging logging, but handlers, etc. are controlled by the parent
import logging
logger = logging.getLogger(__name__)
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
__author__ = 'Cortney T. Buffington, N0MJS'
__copyright__ = 'Copyright (c) 2016-2019 Cortney T. Buffington, N0MJS and the K0USY Group'
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
__license__ = 'GNU GPLv3'
__maintainer__ = 'Cort Buffington, N0MJS'
__email__ = 'n0mjs@me.com'
# Global variables used whether we are a module or __main__
systems = {}
# Timed loop used for reporting HBP status
def config_reports(_config, _factory):
def reporting_loop(_logger, _server):
_logger.debug('(GLOBAL) Periodic reporting loop started')
_server.send_config()
logger.info('(GLOBAL) HBlink TCP reporting server configured')
report_server = _factory(_config)
report_server.clients = []
reactor.listenTCP(_config['REPORTS']['REPORT_PORT'], report_server)
reporting = task.LoopingCall(reporting_loop, logger, report_server)
reporting.start(_config['REPORTS']['REPORT_INTERVAL'])
return report_server
# Shut ourselves down gracefully by disconnecting from the masters and peers.
def hblink_handler(_signal, _frame):
for system in systems:
logger.info('(GLOBAL) SHUTDOWN: DE-REGISTER SYSTEM: %s', system)
systems[system].dereg()
# Check a supplied ID against the ACL provided. Returns action (True|False) based
# on matching and the action specified.
def acl_check(_id, _acl):
id = int_id(_id)
for entry in _acl[1]:
if entry[0] <= id <= entry[1]:
return _acl[0]
return not _acl[0]
#************************************************
# OPENBRIDGE CLASS
#************************************************
class OPENBRIDGE(DatagramProtocol):
def __init__(self, _name, _config, _report):
# Define a few shortcuts to make the rest of the class more readable
self._CONFIG = _config
self._system = _name
self._report = _report
self._config = self._CONFIG['SYSTEMS'][self._system]
self._laststrid = deque([], 20)
def dereg(self):
logger.info('(%s) is mode OPENBRIDGE. No De-Registration required, continuing shutdown', self._system)
def send_system(self, _packet):
if _packet[:4] == DMRD:
#_packet = _packet[:11] + self._config['NETWORK_ID'] + _packet[15:]
_packet = b''.join([_packet[:11], self._config['NETWORK_ID'], _packet[15:]])
#_packet += hmac_new(self._config['PASSPHRASE'],_packet,sha1).digest()
_packet = b''.join([_packet, (hmac_new(self._config['PASSPHRASE'],_packet,sha1).digest())])
self.transport.write(_packet, (self._config['TARGET_IP'], self._config['TARGET_PORT']))
# KEEP THE FOLLOWING COMMENTED OUT UNLESS YOU'RE DEBUGGING DEEPLY!!!!
# logger.debug('(%s) TX Packet to OpenBridge %s:%s -- %s', self._system, self._config['TARGET_IP'], self._config['TARGET_PORT'], ahex(_packet))
else:
logger.error('(%s) OpenBridge system was asked to send non DMRD packet: %s', self._system, _packet)
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
pass
#print(int_id(_peer_id), int_id(_rf_src), int_id(_dst_id), int_id(_seq), _slot, _call_type, _frame_type, repr(_dtype_vseq), int_id(_stream_id))
def datagramReceived(self, _packet, _sockaddr):
# Keep This Line Commented Unless HEAVILY Debugging!
#logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_packet))
if _packet[:4] == DMRD: # DMRData -- encapsulated DMR data frame
_data = _packet[:53]
_hash = _packet[53:]
_ckhs = hmac_new(self._config['PASSPHRASE'],_data,sha1).digest()
if compare_digest(_hash, _ckhs) and _sockaddr == self._config['TARGET_SOCK']:
_peer_id = _data[11:15]
_seq = _data[4]
_rf_src = _data[5:8]
_dst_id = _data[8:11]
_bits = _data[15]
_slot = 2 if (_bits & 0x80) else 1
#_call_type = 'unit' if (_bits & 0x40) else 'group'
if _bits & 0x40:
_call_type = 'unit'
elif (_bits & 0x23) == 0x23:
_call_type = 'vcsbk'
else:
_call_type = 'group'
_frame_type = (_bits & 0x30) >> 4
_dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F
_stream_id = _data[16:20]
#logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id))
# Sanity check for OpenBridge -- all calls must be on Slot 1 for Brandmeister or DMR+. Other HBlinks can process timeslot on OPB if the flag is set
if _slot != 1 and not self._config['BOTH_SLOTS'] and not _call_type == 'unit':
logger.error('(%s) OpenBridge packet discarded because it was not received on slot 1. SID: %s, TGID %s', self._system, int_id(_rf_src), int_id(_dst_id))
return
# ACL Processing
if self._CONFIG['GLOBAL']['USE_ACL']:
if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']):
if _stream_id not in self._laststrid:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', self._system, int_id(_stream_id), int_id(_rf_src))
self._laststrid.append(_stream_id)
return
if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']):
if _stream_id not in self._laststrid:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid.append(_stream_id)
return
if self._config['USE_ACL']:
if not acl_check(_rf_src, self._config['SUB_ACL']):
if _stream_id not in self._laststrid:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', self._system, int_id(_stream_id), int_id(_rf_src))
self._laststrid.append(_stream_id)
return
if not acl_check(_dst_id, self._config['TG1_ACL']):
if _stream_id not in self._laststrid:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid.append(_stream_id)
return
# Userland actions -- typically this is the function you subclass for an application
self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data)
else:
logger.info('(%s) OpenBridge HMAC failed, packet discarded - OPCODE: %s DATA: %s HMAC LENGTH: %s HMAC: %s', self._system, _packet[:4], repr(_packet[:53]), len(_packet[53:]), repr(_packet[53:]))
#************************************************
# HB MASTER CLASS
#************************************************
class HBSYSTEM(DatagramProtocol):
def __init__(self, _name, _config, _report):
# Define a few shortcuts to make the rest of the class more readable
self._CONFIG = _config
self._system = _name
self._report = _report
self._config = self._CONFIG['SYSTEMS'][self._system]
self._laststrid = {1: b'', 2: b''}
# Define shortcuts and generic function names based on the type of system we are
if self._config['MODE'] == 'MASTER':
self._peers = self._CONFIG['SYSTEMS'][self._system]['PEERS']
self.send_system = self.send_peers
self.maintenance_loop = self.master_maintenance_loop
self.datagramReceived = self.master_datagramReceived
self.dereg = self.master_dereg
elif self._config['MODE'] == 'PEER':
self._stats = self._config['STATS']
self.send_system = self.send_master
self.maintenance_loop = self.peer_maintenance_loop
self.datagramReceived = self.peer_datagramReceived
self.dereg = self.peer_dereg
elif self._config['MODE'] == 'XLXPEER':
self._stats = self._config['XLXSTATS']
self.send_system = self.send_master
self.maintenance_loop = self.peer_maintenance_loop
self.datagramReceived = self.peer_datagramReceived
self.dereg = self.peer_dereg
def startProtocol(self):
# Set up periodic loop for tracking pings from peers. Run every 'PING_TIME' seconds
self._system_maintenance = task.LoopingCall(self.maintenance_loop)
self._system_maintenance_loop = self._system_maintenance.start(self._CONFIG['GLOBAL']['PING_TIME'])
# Aliased in __init__ to maintenance_loop if system is a master
def master_maintenance_loop(self):
logger.debug('(%s) Master maintenance loop started', self._system)
remove_list = []
for peer in self._peers:
_this_peer = self._peers[peer]
# Check to see if any of the peers have been quiet (no ping) longer than allowed
if _this_peer['LAST_PING']+(self._CONFIG['GLOBAL']['PING_TIME']*self._CONFIG['GLOBAL']['MAX_MISSED']) < time():
remove_list.append(peer)
for peer in remove_list:
logger.info('(%s) Peer %s (%s) has timed out and is being removed', self._system, self._peers[peer]['CALLSIGN'], self._peers[peer]['RADIO_ID'])
# Remove any timed out peers from the configuration
del self._CONFIG['SYSTEMS'][self._system]['PEERS'][peer]
# Aliased in __init__ to maintenance_loop if system is a peer
def peer_maintenance_loop(self):
logger.debug('(%s) Peer maintenance loop started', self._system)
if self._stats['PING_OUTSTANDING']:
self._stats['NUM_OUTSTANDING'] += 1
# If we're not connected, zero out the stats and send a login request RPTL
if self._stats['CONNECTION'] != 'YES' or self._stats['NUM_OUTSTANDING'] >= self._CONFIG['GLOBAL']['MAX_MISSED']:
self._stats['PINGS_SENT'] = 0
self._stats['PINGS_ACKD'] = 0
self._stats['NUM_OUTSTANDING'] = 0
self._stats['PING_OUTSTANDING'] = False
self._stats['CONNECTION'] = 'RPTL_SENT'
self.send_master(b''.join([RPTL, self._config['RADIO_ID']]))
logger.info('(%s) Sending login request to master %s:%s', self._system, self._config['MASTER_IP'], self._config['MASTER_PORT'])
# If we are connected, sent a ping to the master and increment the counter
if self._stats['CONNECTION'] == 'YES':
self.send_master(b''.join([RPTPING, self._config['RADIO_ID']]))
logger.debug('(%s) RPTPING Sent to Master. Total Sent: %s, Total Missed: %s, Currently Outstanding: %s', self._system, self._stats['PINGS_SENT'], self._stats['PINGS_SENT'] - self._stats['PINGS_ACKD'], self._stats['NUM_OUTSTANDING'])
self._stats['PINGS_SENT'] += 1
self._stats['PING_OUTSTANDING'] = True
def send_peers(self, _packet):
for _peer in self._peers:
self.send_peer(_peer, _packet)
#logger.debug('(%s) Packet sent to peer %s', self._system, self._peers[_peer]['RADIO_ID'])
def send_peer(self, _peer, _packet):
if _packet[:4] == DMRD:
_packet = b''.join([_packet[:11], _peer, _packet[15:]])
self.transport.write(_packet, self._peers[_peer]['SOCKADDR'])
# KEEP THE FOLLOWING COMMENTED OUT UNLESS YOU'RE DEBUGGING DEEPLY!!!!
#logger.debug('(%s) TX Packet to %s on port %s: %s', self._peers[_peer]['RADIO_ID'], self._peers[_peer]['IP'], self._peers[_peer]['PORT'], ahex(_packet))
def send_master(self, _packet):
if _packet[:4] == DMRD:
_packet = b''.join([_packet[:11], self._config['RADIO_ID'], _packet[15:]])
self.transport.write(_packet, self._config['MASTER_SOCKADDR'])
# KEEP THE FOLLOWING COMMENTED OUT UNLESS YOU'RE DEBUGGING DEEPLY!!!!
# logger.debug('(%s) TX Packet to %s:%s -- %s', self._system, self._config['MASTER_IP'], self._config['MASTER_PORT'], ahex(_packet))
def send_xlxmaster(self, radio, xlx, mastersock):
radio3 = int.from_bytes(radio, 'big').to_bytes(3, 'big')
radio4 = int.from_bytes(radio, 'big').to_bytes(4, 'big')
xlx3 = xlx.to_bytes(3, 'big')
streamid = randint(0,255).to_bytes(1, 'big')+randint(0,255).to_bytes(1, 'big')+randint(0,255).to_bytes(1, 'big')+randint(0,255).to_bytes(1, 'big')
# Wait for .5 secs for the XLX to log us in
for packetnr in range(5):
if packetnr < 3:
# First 3 packets, voice start, stream type e1
strmtype = 225
payload = bytearray.fromhex('4f2e00b501ae3a001c40a0c1cc7dff57d75df5d5065026f82880bd616f13f185890000')
else:
# Last 2 packets, voice end, stream type e2
strmtype = 226
payload = bytearray.fromhex('4f410061011e3a781c30a061ccbdff57d75df5d2534425c02fe0b1216713e885ba0000')
packetnr1 = packetnr.to_bytes(1, 'big')
strmtype1 = strmtype.to_bytes(1, 'big')
_packet = b''.join([DMRD, packetnr1, radio3, xlx3, radio4, strmtype1, streamid, payload])
self.transport.write(_packet, mastersock)
# KEEP THE FOLLOWING COMMENTED OUT UNLESS YOU'RE DEBUGGING DEEPLY!!!!
#logger.debug('(%s) XLX Module Change Packet: %s', self._system, ahex(_packet))
return
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
pass
def master_dereg(self):
for _peer in self._peers:
self.send_peer(_peer, MSTCL + _peer)
logger.info('(%s) De-Registration sent to Peer: %s (%s)', self._system, self._peers[_peer]['CALLSIGN'], self._peers[_peer]['RADIO_ID'])
def peer_dereg(self):
self.send_master(RPTCL + self._config['RADIO_ID'])
logger.info('(%s) De-Registration sent to Master: %s:%s', self._system, self._config['MASTER_SOCKADDR'][0], self._config['MASTER_SOCKADDR'][1])
# Aliased in __init__ to datagramReceived if system is a master
def master_datagramReceived(self, _data, _sockaddr):
# Keep This Line Commented Unless HEAVILY Debugging!
# logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data))
# Extract the command, which is various length, all but one 4 significant characters -- RPTCL
_command = _data[:4]
if _command == DMRD: # DMRData -- encapsulated DMR data frame
_peer_id = _data[11:15]
if _peer_id in self._peers \
and self._peers[_peer_id]['CONNECTION'] == 'YES' \
and self._peers[_peer_id]['SOCKADDR'] == _sockaddr:
_seq = _data[4]
_rf_src = _data[5:8]
_dst_id = _data[8:11]
_bits = _data[15]
_slot = 2 if (_bits & 0x80) else 1
#_call_type = 'unit' if (_bits & 0x40) else 'group'
if _bits & 0x40:
_call_type = 'unit'
elif (_bits & 0x23) == 0x23:
_call_type = 'vcsbk'
else:
_call_type = 'group'
_frame_type = (_bits & 0x30) >> 4
_dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F
_stream_id = _data[16:20]
#logger.debug('(%s) DMRD - Seqence: %s, RF Source: %s, Destination ID: %s', self._system, _seq, int_id(_rf_src), int_id(_dst_id))
# ACL Processing
if self._CONFIG['GLOBAL']['USE_ACL']:
if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', self._system, int_id(_stream_id), int_id(_rf_src))
self._laststrid[_slot] = _stream_id
return
if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid[_slot] = _stream_id
return
if _slot == 2 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG2_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid[_slot] = _stream_id
return
if self._config['USE_ACL']:
if not acl_check(_rf_src, self._config['SUB_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', self._system, int_id(_stream_id), int_id(_rf_src))
self._laststrid[_slot] = _stream_id
return
if _slot == 1 and not acl_check(_dst_id, self._config['TG1_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid[_slot] = _stream_id
return
if _slot == 2 and not acl_check(_dst_id, self._config['TG2_ACL']):
if self._laststrid[_slot]!= _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid[_slot] = _stream_id
return
# The basic purpose of a master is to repeat to the peers
if self._config['REPEAT'] == True:
pkt = [_data[:11], '', _data[15:]]
for _peer in self._peers:
if _peer != _peer_id:
pkt[1] = _peer
self.transport.write(b''.join(pkt), self._peers[_peer]['SOCKADDR'])
#logger.debug('(%s) Packet on TS%s from %s (%s) for destination ID %s repeated to peer: %s (%s) [Stream ID: %s]', self._system, _slot, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id), int_id(_dst_id), self._peers[_peer]['CALLSIGN'], int_id(_peer), int_id(_stream_id))
# Userland actions -- typically this is the function you subclass for an application
self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data)
elif _command == RPTL: # RPTLogin -- a repeater wants to login
_peer_id = _data[4:8]
# Check to see if we've reached the maximum number of allowed peers
if len(self._peers) < self._config['MAX_PEERS']:
# Check for valid Radio ID
if acl_check(_peer_id, self._CONFIG['GLOBAL']['REG_ACL']) and acl_check(_peer_id, self._config['REG_ACL']):
# Build the configuration data strcuture for the peer
self._peers.update({_peer_id: {
'CONNECTION': 'RPTL-RECEIVED',
'CONNECTED': time(),
'PINGS_RECEIVED': 0,
'LAST_PING': time(),
'SOCKADDR': _sockaddr,
'IP': _sockaddr[0],
'PORT': _sockaddr[1],
'SALT': randint(0,0xFFFFFFFF),
'RADIO_ID': str(int(ahex(_peer_id), 16)),
'CALLSIGN': '',
'RX_FREQ': '',
'TX_FREQ': '',
'TX_POWER': '',
'COLORCODE': '',
'LATITUDE': '',
'LONGITUDE': '',
'HEIGHT': '',
'LOCATION': '',
'DESCRIPTION': '',
'SLOTS': '',
'URL': '',
'SOFTWARE_ID': '',
'PACKAGE_ID': '',
}})
logger.info('(%s) Repeater Logging in with Radio ID: %s, %s:%s', self._system, int_id(_peer_id), _sockaddr[0], _sockaddr[1])
_salt_str = bytes_4(self._peers[_peer_id]['SALT'])
self.send_peer(_peer_id, b''.join([RPTACK, _salt_str]))
self._peers[_peer_id]['CONNECTION'] = 'CHALLENGE_SENT'
logger.info('(%s) Sent Challenge Response to %s for login: %s', self._system, int_id(_peer_id), self._peers[_peer_id]['SALT'])
else:
self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr)
logger.warning('(%s) Invalid Login from %s Radio ID: %s Denied by Registation ACL', self._system, _sockaddr[0], int_id(_peer_id))
else:
self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr)
logger.warning('(%s) Registration denied from Radio ID: %s Maximum number of peers exceeded', self._system, int_id(_peer_id))
elif _command == RPTK: # Repeater has answered our login challenge
_peer_id = _data[4:8]
if _peer_id in self._peers \
and self._peers[_peer_id]['CONNECTION'] == 'CHALLENGE_SENT' \
and self._peers[_peer_id]['SOCKADDR'] == _sockaddr:
_this_peer = self._peers[_peer_id]
_this_peer['LAST_PING'] = time()
_sent_hash = _data[8:]
_salt_str = bytes_4(_this_peer['SALT'])
_calc_hash = bhex(sha256(_salt_str+self._config['PASSPHRASE']).hexdigest())
if _sent_hash == _calc_hash:
_this_peer['CONNECTION'] = 'WAITING_CONFIG'
self.send_peer(_peer_id, b''.join([RPTACK, _peer_id]))
logger.info('(%s) Peer %s has completed the login exchange successfully', self._system, _this_peer['RADIO_ID'])
else:
logger.info('(%s) Peer %s has FAILED the login exchange successfully', self._system, _this_peer['RADIO_ID'])
self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr)
del self._peers[_peer_id]
else:
self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr)
logger.warning('(%s) Login challenge from Radio ID that has not logged in: %s', self._system, int_id(_peer_id))
elif _command == RPTC: # Repeater is sending it's configuraiton OR disconnecting
if _data[:5] == RPTCL: # Disconnect command
_peer_id = _data[5:9]
if _peer_id in self._peers \
and self._peers[_peer_id]['CONNECTION'] == 'YES' \
and self._peers[_peer_id]['SOCKADDR'] == _sockaddr:
logger.info('(%s) Peer is closing down: %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id))
self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr)
del self._peers[_peer_id]
else:
_peer_id = _data[4:8] # Configure Command
if _peer_id in self._peers \
and self._peers[_peer_id]['CONNECTION'] == 'WAITING_CONFIG' \
and self._peers[_peer_id]['SOCKADDR'] == _sockaddr:
_this_peer = self._peers[_peer_id]
_this_peer['CONNECTION'] = 'YES'
_this_peer['CONNECTED'] = time()
_this_peer['LAST_PING'] = time()
_this_peer['CALLSIGN'] = _data[8:16]
_this_peer['RX_FREQ'] = _data[16:25]
_this_peer['TX_FREQ'] = _data[25:34]
_this_peer['TX_POWER'] = _data[34:36]
_this_peer['COLORCODE'] = _data[36:38]
_this_peer['LATITUDE'] = _data[38:46]
_this_peer['LONGITUDE'] = _data[46:55]
_this_peer['HEIGHT'] = _data[55:58]
_this_peer['LOCATION'] = _data[58:78]
_this_peer['DESCRIPTION'] = _data[78:97]
_this_peer['SLOTS'] = _data[97:98]
_this_peer['URL'] = _data[98:222]
_this_peer['SOFTWARE_ID'] = _data[222:262]
_this_peer['PACKAGE_ID'] = _data[262:302]
self.send_peer(_peer_id, b''.join([RPTACK, _peer_id]))
logger.info('(%s) Peer %s (%s) has sent repeater configuration', self._system, _this_peer['CALLSIGN'], _this_peer['RADIO_ID'])
else:
self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr)
logger.warning('(%s) Peer info from Radio ID that has not logged in: %s', self._system, int_id(_peer_id))
elif _command == RPTP: # RPTPing -- peer is pinging us
_peer_id = _data[7:11]
if _peer_id in self._peers \
and self._peers[_peer_id]['CONNECTION'] == "YES" \
and self._peers[_peer_id]['SOCKADDR'] == _sockaddr:
self._peers[_peer_id]['PINGS_RECEIVED'] += 1
self._peers[_peer_id]['LAST_PING'] = time()
self.send_peer(_peer_id, b''.join([MSTPONG, _peer_id]))
logger.debug('(%s) Received and answered RPTPING from peer %s (%s)', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id))
else:
self.transport.write(b''.join([MSTNAK, _peer_id]), _sockaddr)
logger.warning('(%s) Ping from Radio ID that is not logged in: %s', self._system, int_id(_peer_id))
elif _command == RPTO:
_peer_id = _data[4:8]
if _peer_id in self._peers \
and self._peers[_peer_id]['CONNECTION'] == 'YES' \
and self._peers[_peer_id]['SOCKADDR'] == _sockaddr:
logger.info('(%s) Peer %s (%s) has send options: %s', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_peer_id), _data[8:])
self.transport.write(b''.join([RPTACK, _peer_id]), _sockaddr)
elif _command == DMRA:
_peer_id = _data[4:8]
logger.info('(%s) Recieved DMR Talker Alias from peer %s, subscriber %s', self._system, self._peers[_peer_id]['CALLSIGN'], int_id(_rf_src))
else:
logger.error('(%s) Unrecognized command. Raw HBP PDU: %s', self._system, ahex(_data))
# Aliased in __init__ to datagramReceived if system is a peer
def peer_datagramReceived(self, _data, _sockaddr):
# Keep This Line Commented Unless HEAVILY Debugging!
# logger.debug('(%s) RX packet from %s -- %s', self._system, _sockaddr, ahex(_data))
# Validate that we receveived this packet from the master - security check!
if self._config['MASTER_SOCKADDR'] == _sockaddr:
# Extract the command, which is various length, but only 4 significant characters
_command = _data[:4]
if _command == DMRD: # DMRData -- encapsulated DMR data frame
_peer_id = _data[11:15]
if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation
_seq = _data[4:5]
_rf_src = _data[5:8]
_dst_id = _data[8:11]
_bits = _data[15]
_slot = 2 if (_bits & 0x80) else 1
#_call_type = 'unit' if (_bits & 0x40) else 'group'
if _bits & 0x40:
_call_type = 'unit'
elif (_bits & 0x23) == 0x23:
_call_type = 'vcsbk'
else:
_call_type = 'group'
_frame_type = (_bits & 0x30) >> 4
_dtype_vseq = (_bits & 0xF) # data, 1=voice header, 2=voice terminator; voice, 0=burst A ... 5=burst F
_stream_id = _data[16:20]
#logger.debug('(%s) DMRD - Sequence: %s, RF Source: %s, Destination ID: %s', self._system, int_id(_seq), int_id(_rf_src), int_id(_dst_id))
# ACL Processing
if self._CONFIG['GLOBAL']['USE_ACL']:
if not acl_check(_rf_src, self._CONFIG['GLOBAL']['SUB_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY GLOBAL ACL', self._system, int_id(_stream_id), int_id(_rf_src))
self._laststrid[_slot] = _stream_id
return
if _slot == 1 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG1_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid[_slot] = _stream_id
return
if _slot == 2 and not acl_check(_dst_id, self._CONFIG['GLOBAL']['TG2_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY GLOBAL TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid[_slot] = _stream_id
return
if self._config['USE_ACL']:
if not acl_check(_rf_src, self._config['SUB_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s FROM SUBSCRIBER %s BY SYSTEM ACL', self._system, int_id(_stream_id), int_id(_rf_src))
self._laststrid[_slot] = _stream_id
return
if _slot == 1 and not acl_check(_dst_id, self._config['TG1_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS1 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid[_slot] = _stream_id
return
if _slot == 2 and not acl_check(_dst_id, self._config['TG2_ACL']):
if self._laststrid[_slot] != _stream_id:
logger.info('(%s) CALL DROPPED WITH STREAM ID %s ON TGID %s BY SYSTEM TS2 ACL', self._system, int_id(_stream_id), int_id(_dst_id))
self._laststrid[_slot] = _stream_id
return
# Userland actions -- typically this is the function you subclass for an application
self.dmrd_received(_peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data)
elif _command == MSTN: # Actually MSTNAK -- a NACK from the master
_peer_id = _data[6:10]
if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation
logger.warning('(%s) MSTNAK Received. Resetting connection to the Master.', self._system)
self._stats['CONNECTION'] = 'NO' # Disconnect ourselves and re-register
self._stats['CONNECTED'] = time()
elif _command == RPTA: # Actually RPTACK -- an ACK from the master
# Depending on the state, an RPTACK means different things, in each clause, we check and/or set the state
if self._stats['CONNECTION'] == 'RPTL_SENT': # If we've sent a login request...
_login_int32 = _data[6:10]
logger.info('(%s) Repeater Login ACK Received with 32bit ID: %s', self._system, int_id(_login_int32))
_pass_hash = sha256(b''.join([_login_int32, self._config['PASSPHRASE']])).hexdigest()
_pass_hash = bhex(_pass_hash)
self.send_master(b''.join([RPTK, self._config['RADIO_ID'], _pass_hash]))
self._stats['CONNECTION'] = 'AUTHENTICATED'
elif self._stats['CONNECTION'] == 'AUTHENTICATED': # If we've sent the login challenge...
_peer_id = _data[6:10]
if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation
logger.info('(%s) Repeater Authentication Accepted', self._system)
_config_packet = b''.join([\
self._config['RADIO_ID'],\
self._config['CALLSIGN'],\
self._config['RX_FREQ'],\
self._config['TX_FREQ'],\
self._config['TX_POWER'],\
self._config['COLORCODE'],\
self._config['LATITUDE'],\
self._config['LONGITUDE'],\
self._config['HEIGHT'],\
self._config['LOCATION'],\
self._config['DESCRIPTION'],\
self._config['SLOTS'],\
self._config['URL'],\
self._config['SOFTWARE_ID'],\
self._config['PACKAGE_ID']\
])
self.send_master(b''.join([RPTC, _config_packet]))
self._stats['CONNECTION'] = 'CONFIG-SENT'
logger.info('(%s) Repeater Configuration Sent', self._system)
else:
self._stats['CONNECTION'] = 'NO'
logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system)
elif self._stats['CONNECTION'] == 'CONFIG-SENT': # If we've sent out configuration to the master
_peer_id = _data[6:10]
if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation
logger.info('(%s) Repeater Configuration Accepted', self._system)
if self._config['OPTIONS']:
self.send_master(b''.join([RPTO, self._config['RADIO_ID'], self._config['OPTIONS']]))
self._stats['CONNECTION'] = 'OPTIONS-SENT'
logger.info('(%s) Sent options: (%s)', self._system, self._config['OPTIONS'])
else:
self._stats['CONNECTION'] = 'YES'
self._stats['CONNECTED'] = time()
logger.info('(%s) Connection to Master Completed', self._system)
# If we are an XLX, send the XLX module request here.
if self._config['MODE'] == 'XLXPEER':
self.send_xlxmaster(self._config['RADIO_ID'], int(4000), self._config['MASTER_SOCKADDR'])
self.send_xlxmaster(self._config['RADIO_ID'], self._config['XLXMODULE'], self._config['MASTER_SOCKADDR'])
logger.info('(%s) Sending XLX Module request', self._system)
else:
self._stats['CONNECTION'] = 'NO'
logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system)
elif self._stats['CONNECTION'] == 'OPTIONS-SENT': # If we've sent out options to the master
_peer_id = _data[6:10]
if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation
logger.info('(%s) Repeater Options Accepted', self._system)
self._stats['CONNECTION'] = 'YES'
self._stats['CONNECTED'] = time()
logger.info('(%s) Connection to Master Completed with options', self._system)
else:
self._stats['CONNECTION'] = 'NO'
logger.error('(%s) Master ACK Contained wrong ID - Connection Reset', self._system)
elif _command == MSTP: # Actually MSTPONG -- a reply to RPTPING (send by peer)
_peer_id = _data[7:11]
if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation
self._stats['PING_OUTSTANDING'] = False
self._stats['NUM_OUTSTANDING'] = 0
self._stats['PINGS_ACKD'] += 1
logger.debug('(%s) MSTPONG Received. Pongs Since Connected: %s', self._system, self._stats['PINGS_ACKD'])
elif _command == MSTC: # Actually MSTCL -- notify us the master is closing down
_peer_id = _data[5:9]
if self._config['LOOSE'] or _peer_id == self._config['RADIO_ID']: # Validate the Radio_ID unless using loose validation
self._stats['CONNECTION'] = 'NO'
logger.info('(%s) MSTCL Recieved', self._system)
else:
logger.error('(%s) Received an invalid command in packet: %s', self._system, ahex(_data))
#
# Socket-based reporting section
#
class report(NetstringReceiver):
def __init__(self, factory):
self._factory = factory
def connectionMade(self):
self._factory.clients.append(self)
logger.info('(REPORT) HBlink reporting client connected: %s', self.transport.getPeer())
def connectionLost(self, reason):
logger.info('(REPORT) HBlink reporting client disconnected: %s', self.transport.getPeer())
self._factory.clients.remove(self)
def stringReceived(self, data):
self.process_message(data)
def process_message(self, _message):
opcode = _message[:1]
if opcode == REPORT_OPCODES['CONFIG_REQ']:
logger.info('(REPORT) HBlink reporting client sent \'CONFIG_REQ\': %s', self.transport.getPeer())
self.send_config()
else:
logger.error('(REPORT) got unknown opcode')
class reportFactory(Factory):
def __init__(self, config):
self._config = config
def buildProtocol(self, addr):
if (addr.host) in self._config['REPORTS']['REPORT_CLIENTS'] or '*' in self._config['REPORTS']['REPORT_CLIENTS']:
logger.debug('(REPORT) Permitting report server connection attempt from: %s:%s', addr.host, addr.port)
return report(self)
else:
logger.error('(REPORT) Invalid report server connection attempt from: %s:%s', addr.host, addr.port)
return None
def send_clients(self, _message):
for client in self.clients:
client.sendString(_message)
def send_config(self):
serialized = pickle.dumps(self._config['SYSTEMS'], protocol=2) #.decode('utf-8', errors='ignore') #pickle.HIGHEST_PROTOCOL)
self.send_clients(b''.join([REPORT_OPCODES['CONFIG_SND'], serialized]))
# ID ALIAS CREATION
# Download
def mk_aliases(_config):
if _config['ALIASES']['TRY_DOWNLOAD'] == True:
# Try updating peer aliases file
result = try_download(_config['ALIASES']['PATH'], _config['ALIASES']['PEER_FILE'], _config['ALIASES']['PEER_URL'], _config['ALIASES']['STALE_TIME'])
logger.info('(GLOBAL) %s', result)
# Try updating subscriber aliases file
result = try_download(_config['ALIASES']['PATH'], _config['ALIASES']['SUBSCRIBER_FILE'], _config['ALIASES']['SUBSCRIBER_URL'], _config['ALIASES']['STALE_TIME'])
logger.info('(GLOBAL) %s', result)
# Make Dictionaries
peer_ids = mk_id_dict(_config['ALIASES']['PATH'], _config['ALIASES']['PEER_FILE'])
if peer_ids:
logger.info('(GLOBAL) ID ALIAS MAPPER: peer_ids dictionary is available')
subscriber_ids = mk_id_dict(_config['ALIASES']['PATH'], _config['ALIASES']['SUBSCRIBER_FILE'])
if subscriber_ids:
logger.info('(GLOBAL) ID ALIAS MAPPER: subscriber_ids dictionary is available')
talkgroup_ids = mk_id_dict(_config['ALIASES']['PATH'], _config['ALIASES']['TGID_FILE'])
if talkgroup_ids:
logger.info('(GLOBAL) ID ALIAS MAPPER: talkgroup_ids dictionary is available')
return peer_ids, subscriber_ids, talkgroup_ids
#************************************************
# MAIN PROGRAM LOOP STARTS HERE
#************************************************
if __name__ == '__main__':
# Python modules we need
import argparse
import sys
import os
import signal
# Change the current directory to the location of the application
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually hblink.cfg)')
parser.add_argument('-l', '--logging', action='store', dest='LOG_LEVEL', help='Override config file logging level.')
cli_args = parser.parse_args()
# Ensure we have a path for the config file, if one wasn't specified, then use the execution directory
if not cli_args.CONFIG_FILE:
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/hblink.cfg'
# Call the external routine to build the configuration dictionary
CONFIG = config.build_config(cli_args.CONFIG_FILE)
# Call the external routing to start the system logger
if cli_args.LOG_LEVEL:
CONFIG['LOGGER']['LOG_LEVEL'] = cli_args.LOG_LEVEL
logger = log.config_logging(CONFIG['LOGGER'])
logger.info('\n\nCopyright (c) 2013, 2014, 2015, 2016, 2018, 2019, 2020\n\tThe Regents of the K0USY Group. All rights reserved.\n')
logger.debug('(GLOBAL) Logging system started, anything from here on gets logged')
# Set up the signal handler
def sig_handler(_signal, _frame):
logger.info('(GLOBAL) SHUTDOWN: HBLINK IS TERMINATING WITH SIGNAL %s', str(_signal))
hblink_handler(_signal, _frame)
logger.info('(GLOBAL) SHUTDOWN: ALL SYSTEM HANDLERS EXECUTED - STOPPING REACTOR')
reactor.stop()
# Set signal handers so that we can gracefully exit if need be
for sig in [signal.SIGTERM, signal.SIGINT]:
signal.signal(sig, sig_handler)
peer_ids, subscriber_ids, talkgroup_ids = mk_aliases(CONFIG)
# INITIALIZE THE REPORTING LOOP
if CONFIG['REPORTS']['REPORT']:
report_server = config_reports(CONFIG, reportFactory)
else:
report_server = None
logger.info('(REPORT) TCP Socket reporting not configured')
# HBlink instance creation
logger.info('(GLOBAL) HBlink \'HBlink.py\' -- SYSTEM STARTING...')
for system in CONFIG['SYSTEMS']:
if CONFIG['SYSTEMS'][system]['ENABLED']:
if CONFIG['SYSTEMS'][system]['MODE'] == 'OPENBRIDGE':
systems[system] = OPENBRIDGE(system, CONFIG, report_server)
else:
systems[system] = HBSYSTEM(system, CONFIG, report_server)
reactor.listenUDP(CONFIG['SYSTEMS'][system]['PORT'], systems[system], interface=CONFIG['SYSTEMS'][system]['IP'])
logger.debug('(GLOBAL) %s instance created: %s, %s', CONFIG['SYSTEMS'][system]['MODE'], system, systems[system])
reactor.run()

203
index.md Normal file
View File

@ -0,0 +1,203 @@
# GPS/Data Application
----
## [Home](https://kf7eel.github.io/hblink3/) | [Configuration](/hblink3/config_doc.html) | [API Documentation](https://kf7eel.github.io/hblink3/api_doc.html) | [HBlink Website](https://hblink-org.github.io/)
----
This is a **fork** of the [HBLink](https://hblink-org.github.io/) project that supports APRS and DMR SMS functions.
This repository contains everything needed to decode DMR GPS packets and SMS for HBLink3. This application can act as a master or peer and receive data as a group call or private call. It is designed to work in a multi system/user network.
Files modified from original master branch of HBLink3:
* bridge.py
* config.py
#### Required modules
* pynmea2
* aprslib
* maidenhead
#### Optional Modules
* Flask - Required for dashboard
* smtplib - Required for sending email. If pip fails to install module, it may already be installed as most Linux distrobutions have this module by default.
* slixmpp - Required for upcoming XMPP gateway.
This should work for DMR radios that send location data as a UTF-8 NMEA sentence. I am hopping to add support for more radios in the future.
### Differences in branches
* **GPS**: Contains the GPS/Data Application.
* **aprs_features**: Contains the GPS/Data Application and a modified version of the APRS implementation for repeaters and hotspots by **IU7IGU**. (See [https://github.com/iu7igu/hblink3-aprs](https://github.com/iu7igu/hblink3-aprs) for his work). I combined these for convenience.
* **termux**: Tweaked version of this project that will run on Android in [Termux](https://termux.com/). **This branch is a WORK IN PROGRESS.**
## Confirmed working:
Actually tested
| Radio | GPS | SMS |
|-------|:---:|:---:|
| Anytone D878| YES | YES |
| Anytone D578| YES | YES |
| BTech DMR-6x2 | YES | Most likely |
| MD-380 (MD380tools, no GPS) | - | YES |
| MD-380 (stock firmware, GPS) | YES | Most likely |
| MD-390 (stock firmware) | YES | YES |
| Retevis RT73* | YES | YES |
| Ailunce HD1 | YES | YES |
*RT73 must have unconfirmed data setting enabled.
## Highly suspected to work:
Not tested yet, but will most likely work.
| Radio | GPS | SMS |
|-------|:---:|:---:|
| Anytone D868 | Most likely | Most likely |
| TYT MD-2017 | Most likely | Likely |
| TYT MD-9600 | Most likely | Likely |
| Retevis RT8 | Most likely | Likely |
## Tested, but with issues.
Tested, but with bugs present.
| Radio | GPS | SMS |
|-------|:---:|:---:|
| Alinco DJ-MD5TGP | WIP | Most likely |
| Motorola DP3601| WIP | WIP |
## Would like to test:
Connect Systems GPS enabled radios
## Features
* Decode GPS locations and upload APRS position packets
* Each user/DMR ID can customize APRS position
* Ability to receive data as a private call or group call
* Trigger a command or script via DMR SMS
* Optional web dashboard to show APRS packets uploaded
* Display bulletins sent via SMS on web dashboard
## How it works
A user should configure their radio for the DMR ID of the application and private or group call. When a position is received by the application, it will extract the coordinates and create an APRS position packet. The application will find the callsign of the user based on the sending radio's DMR ID. It is essential to have an up to date subscriber_ids file for this to work. A predefined APRS SSID is appended to the callsign. The APRS location packet is then uploaded to APRS-IS. No setup is required beforehand on the part of the user. This is pretty much "plug and play."
For example, N0CALL has a DMR ID of 1234567. N0CALL's radio sends a position to the application. The application will query the subscriber_ids file for DMR ID 1234567. The result will be N0CALL. An APRS location pack is created and uploaded to APRS-IS.
## Individual user/DMR ID APRS settings
By default, all APRS positions will have an SSID of 15, a default comment, and the callsign of the DMR user. These default settings can be changed.
The comment, SSID, and icon can be set for each individual user/DMR ID the application sees. The application stores all the setting in a file. You may have different SSIDs, icons, and comments for different DMR IDs. This is done via DMR SMS using the following commands:
| Command | Description | Example |
|-------|:---:|:---:|
|**@SSID**|Change SSID of user callsign.|`@SSID 7`|
|**@ICON**|Change the icon of the APRS position. *See [http://aprs.net/vm/DOS/SYMBOLS.HTM](http://aprs.net/vm/DOS/SYMBOLS.HTM) for icon list.|`@icon /p`|
|**@COM**|Change the comment of the APRS.|`@COM This is a test comment.`|
|**@MH**|Set you location by maidenhead grid square. Designed for radios with no GPS or that are not compatable yet.|`@MH DN97uk`|
|**@BB**|Post a bulliten to the web dashboard.|`@BB This is a test bulletin.`|
|**@[CALLSIGN W/ SSID] A-[MESSAGE]**|Send a message to another station via APRS.|`@N0CALL-15 A-This is a test.`|
|**[EMAIL ADDRESS] E-[MESSAGE]**|Send an email to an email address.|`test@example.org E-This is a test.`|
|**@SOS**|Any SMS with @SOS in it will trigger an EMERGENCY notice on the dashboard|`@SOS THIS IS ONLY A TEST`|
|**@NOTICE**|Any SMS with @NOTICE in it will trigger a notice on the dashboard, can be used to test EMERGENCY function.|`@NOTICE THIS IS ONLY A TEST`|
|**@REM SOS**|Removes EMERGENCY or general notice from dashboard.|`@REM SOS`|
Send a DMR SMS to the configured dmr_data_id in the application with the desired command followed by the value. For example, to change your icon to a dog, the command would be `@ICON /p` (see the icon table for values). Changing your SSID is as simple as `@SSID 7`, and `@COM Testing 123` will change the comment.
Sending `@BB Test` will result in a post to the bulletin board with the messaage of "Test".
**To remove any of the stored values, just send the appropriate command without any input.** `@COM` will remove the stored comment, `@ICON` will remove the stored icon, and `@COM` will remove the strored comment. Any position now reports sent will have the default settings.
# Web Dashboard
The web dashboard is completely optional. Python module flask is required for this to work. The web dashboard will display the last 15 positions of radios sent to APRS-IS. The dashboard will also sh user bulletin. A bulletin is a message sent via SMS that will display on the web dashboard. There are several uses for this, including: testing SMS functionality of radio, announcements, and moire. It is a novel feature. The page will automatically reload every 2 minutes. Setup is rather simple. Just modify the example config in the dashboard directory and rename it to dashboard_settings.py. Then start dashboard.py.
### Dashboard Features
* View the Latitude and Longitude of sent positions
* Post short messages to a bulletin board
* View Bulletin Board messages as an RSS feed
* Plot received positions on a map
* Activate an EMERGENCY message on the dashboard.
### Dashboard Screenshots
![Main Page](https://github.com/kf7eel/hblink3/raw/gh-pages/normal.png)
---
![Map](https://github.com/kf7eel/hblink3/raw/gh-pages/map2.png)
---
![Emergency](https://github.com/kf7eel/hblink3/raw/gh-pages/emergency_screen.png)
## APRS messaging
**At this time, only sending of messages from DMR SMS to APRS-IS is supported.** I find this feature very pointless because it will only go one way, but someone else may find it important. **Messages from sent from APRS-IS to DMR SMS will not work.** I have not written the code for this yet. It will likley be a long time before this is a possibility.
## APRS TOCALL
The project was granted a [tocall](http://www.aprs.org/aprs11/tocalls.txt) of **APHBLx** by Bob Bruniga, WB4APR. This will identify that your APRS position came from HBLink. The x on the end can be any letter/number. Here are the current designations of APHBLx:
* **APHBL3** - HBlink3 D-APRS gateway
* **APHBLD** - DMRlink D-APRS gateway (the IPSC version of the project)
* **_APHBLS_** - Planned, but not in use: HBLink3 via KISS TNC
## Configuration
See hblink_SAMPLE.cfg, rules_SAMPLE.py, and gps_data_SAMPLE.cfg for examples.
## Special thanks to:
**N0MJS** - For creating HBLink and dmr_utils. This project not possible without him.
**IU7IGU** - For creating APRS position beaconing for PEER connections.
**IV3JDV** - For helping debug SMS in Anytone radios.
**KD7LMN** - For pointing out a critical bug.
**KB5PBM** - For helping implement support for MD-380 type radios.
**EI7IG** - For writing the page explaining MD-380 type GPS packets.
**M0GLJ** - For assisting with Motorola testing.
## Resources for DMR data
I spent many hours looking at the following for this project. You may find these links useful.
https://github.com/travisgoodspeed/md380tools/issues/160
https://jpronans.github.io/ei7ig/dmr.html
http://cloud.dstar.su/files/G4KLX/MMDVM/MMDVM%20Specification%2020150922.pdf
https://wiki.brandmeister.network/index.php/NMEA_Location_Reporting
https://forums.radioreference.com/threads/motorola-lrrp-protocol.370081/
https://forums.radioreference.com/threads/lrrp-decoding.359575/
https://github.com/polkabana/go-dmr
https://github.com/nonoo/dmrshark
https://wiki.brandmeister.network/index.php/Compressed_Location_Reporting
All of the ETSI DMR documents (ETSI 102 361-1 through 361-4).
The Shark RF forums.
---

118
install.md Normal file
View File

@ -0,0 +1,118 @@
# Installation
----
## [Home](https://kf7eel.github.io/hblink3/) | [Installation/Configuration](/hblink3/install.html) | [HBlink Website](https://hblink-org.github.io/)
----
## WORK IN PROGRESS
### Note about different branches:
There are three different branches to the project. All three branches contain hblink and the D-APRS application. The **gps** branch contains the D-APRS application. The **aprs_features** branch contains the D-APRS application _and_ a modification to allow the beaconing of the location of connected peers, authored by **IU7IGU**. The **termux** branch is optimized to run on Android.
# Installation
Clone the git repository.
`git clone https://github.com/kf7eel/hblink3`
Change directory to hblink3.
`cd hblink3`
Install the required modules.
`python3 -m pip install -r requirements.txt`
_**Note: Ignore any errors regarding smtplib or traceback as those modules come by default on most Linux distributions.**_
# Configuration
There are 2 diferent ways to run the application.
First, it can be run as a client, think of it as a receive only DMR hotspot. This is useful for operators who just want
to add APRS functionality to a network. This is the simplest approach and allows for the greatest flexibility for implementing the gateway.
The second method is designed for small networks and is highly experimental. Rather than adding the application as a client, the gateway is included in bridge.py. This allows for much simpler configuration, and theoretically would
handle multiple position transmissions at the same time. However, it is not know how well it will scale up and what processor resources are required, use at your own risk.
**It is reccommended to run the gateway as a client.**
A stanza is a section of the configuration file that begins with brackets (example: **[GLOBAL]**). A MASTER stanza is a section of the configuration that will accept incomming connections from clients (peers). A PEER stanza is a section of configuration that will connect to another MMDVM server. Below is a summary of each stanza found in the configuration. **For more detailed definitions, see the example configurations.**
**[GLOBAL]**
Contains settings for ACLs (access control) for the whole server. You also configure the path to configuration files and subscriber_ids here (leave as default).
**[REPORTS]**
Contains settings for network reporting. HBmonitor uses this. Leave as default.
**[LOGGER]**
Contains settings for logging to file, console, etc. Set log level here. Leave as default.
**[GPS_DATA]**
**Note: The GPS_DATA stanza is only required in the configuration file that gps_data.py will be using.**
DATA_DMR_ID - This is the DMR ID that users send DMR GPS data.
CALL_TYPE - group, unit, or both. Group if you want users to send data to a talkgroup, unit if you want users to send data as a private call, or both if you want both options.
USER_APRS_SSID - Default APRS SSID assigned to user APRS positions.
USER_APRS_COMMENT - Default Comment attached to user APRS positions.
APRS_LOGIN_CALL, PASSCODE, SERVER, and PORT - Login settings for APRS-IS. Setting APRS_LOGIN_CALL to N0CALL will cause the gateway to not upload packets to APRS server.
The IGATE settings are only applicable if you are using the gps_data_beacon_igate script. The gps_data_beacon_igate script uploads the position of the gateway as configured. This will cause APRS clients (such as aprs.fi) to see the gateway as an igate and keep statistics about it. The igate script does not effect the operation gps_data itself. Time in minutes.
The email gateway settings are OPTIONAL. They are NOT REQUIRED if you don't want to enable the email gateway. Leave as is to disable.
**[ALIASES]**
This is the configuration for downloading the latest DMR ID database from radioid.net. Default setting will fetch new DB every 7 days.
_**See notes below to continue configuration**_
### D-APRS as a client
Copy gps_data-SAMPLE.cfg to gps_data.cfg. Add a PEER stanza to connect to your network via MMDVM connection. Connecting the gateway to your network as a PEER is a fairly simple process. Add a MASTER stanza in you network configuration and call it something like "D-APRS". This is the MASTER that you will connect the gateway to as a client. You will need to modify rules.py on your network to allow the desired talkgroup/private calling to route to the gateway via MMDVM connection.
You could also set a MASTER stanza and connect your network as a PEER. This is more suited for advanced users.
Mention rules.py
#### gps branch
No more configuration reguired.
#### aprs_features branch
Modify the APRS stanza to your liking.
**[APRS]**
**Note: This APRS stanza only applies to the _aprs_features_ beanch of the project. It is requires for beaconing the position of connected peers (repeaters or hotspots) and does not affect any GPS data from radios. This stanza only needs to be in hblink.cfg.**
This stanza contains the settings for APRS-IS, this stanza only applies to the **_aprs_features_** branch. When beaconing the location of a connected hotspot or repeater (not GPS location of a radio), the settings here are used.
You will also need to add **APRS: True** (or False) to each of your MASTER stanzas in hblink.cfg. Setting to false will disable the reporting of PEER locations (repeaters or hotspots) on the current MASTER stanza.
See example hblink-SAMPLE.cfg in **aprs_features** branch.
### D-APRS built into bridge.py
Using this method, there is no need to have a gps_data.cfg file, or separate script running. The D-APRS gateway is "baked" into bridge.py. This is also much simpler to configure.
Simply modify hblink.cfg to your liking, ensuring that the GPS_DATA stanza is in hblink.cfg. If you are using the **aprs_features** branch, ensuse that the APRS stanza is in hblink.cfg and that **APRS: True** (or false) is in each MASTER stanza. Thats it. See hblink-SAMPLE.cfg in **aprs_features** branch.

View File

@ -1,5 +0,0 @@
#! /bin/bash
# Install the required support programs
apt-get install python3 python3-pip -y
pip3 install -r requirements.txt

93
log.py
View File

@ -1,93 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2018 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
This is the logging configuration for hblink.py. It changes very infrequently,
so keeping in a separate module keeps hblink.py more concise. this file is
likely to never change.
'''
import logging
from logging.config import dictConfig
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
__author__ = 'Cortney T. Buffington, N0MJS'
__copyright__ = 'Copyright (c) 2016-2018 Cortney T. Buffington, N0MJS and the K0USY Group'
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
__license__ = 'GNU GPLv3'
__maintainer__ = 'Cort Buffington, N0MJS'
__email__ = 'n0mjs@me.com'
def config_logging(_logger):
dictConfig({
'version': 1,
'disable_existing_loggers': False,
'filters': {
},
'formatters': {
'verbose': {
'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
},
'timed': {
'format': '%(levelname)s %(asctime)s %(message)s'
},
'simple': {
'format': '%(levelname)s %(message)s'
},
'syslog': {
'format': '%(name)s (%(process)d): %(levelname)s %(message)s'
}
},
'handlers': {
'null': {
'class': 'logging.NullHandler'
},
'console': {
'class': 'logging.StreamHandler',
'formatter': 'simple'
},
'console-timed': {
'class': 'logging.StreamHandler',
'formatter': 'timed'
},
'file': {
'class': 'logging.FileHandler',
'formatter': 'simple',
'filename': _logger['LOG_FILE'],
},
'file-timed': {
'class': 'logging.FileHandler',
'formatter': 'timed',
'filename': _logger['LOG_FILE'],
},
'syslog': {
'class': 'logging.handlers.SysLogHandler',
'formatter': 'syslog',
}
},
'root': {
'handlers': _logger['LOG_HANDLERS'].split(','),
'level': _logger['LOG_LEVEL'],
'propagate': True,
},
})
return logging.getLogger(_logger['LOG_NAME'])

BIN
map2.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

View File

@ -1,105 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
from bitarray import bitarray
from dmr_utils3 import bptc, golay, qr
from dmr_utils3.utils import bytes_3, bytes_4
from dmr_utils3.const import EMB, SLOT_TYPE, BS_VOICE_SYNC, BS_DATA_SYNC, LC_OPT
from random import randint
from voice_lib import words
# Precalculated "dmrbits" (DMRD packet byte 15) -- just (slot << 7 | this value) and you're good to go!
HEADBITS = 0b00100001
BURSTBITS = [0b00010000,0b00000001,0b00000010,0b00000011,0b00000100,0b00000101]
TERMBITS = 0b00100010
# Need a bitstring of 4-bytes of zero for burst F
NULL_EMB_LC = bitarray(endian='big')
NULL_EMB_LC.frombytes(b'\x00\x00\x00\x00')
# This is where HBP encodes RSSI, it will need to be null
TAIL = b'\x00\x00'
# WARNING this funciton uses yeild to return a generator that will pass the next HBP packet for a phrase
# each time that it is called. Do NOT try to use it like a normal function.
def pkt_gen(_rf_src, _dst_id, _peer, _slot, _phrase):
# Calculate all of the static components up-front
STREAM_ID = bytes_4(randint(0x00, 0xFFFFFFFF))
SDP = _rf_src + _dst_id + _peer
LC = LC_OPT + _dst_id + _rf_src
HEAD_LC = bptc.encode_header_lc(LC)
HEAD_LC = [HEAD_LC[:98], HEAD_LC[-98:]]
TERM_LC = bptc.encode_terminator_lc(LC)
TERM_LC = [TERM_LC[:98], TERM_LC[-98:]]
EMB_LC = bptc.encode_emblc(LC)
EMBED = []
EMBED.append( BS_VOICE_SYNC )
EMBED.append(EMB['BURST_B'][:8] + EMB_LC[1] + EMB['BURST_B'][-8:])
EMBED.append(EMB['BURST_C'][:8] + EMB_LC[2] + EMB['BURST_C'][-8:])
EMBED.append(EMB['BURST_D'][:8] + EMB_LC[3] + EMB['BURST_D'][-8:])
EMBED.append(EMB['BURST_E'][:8] + EMB_LC[4] + EMB['BURST_E'][-8:])
EMBED.append(EMB['BURST_F'][:8] + NULL_EMB_LC + EMB['BURST_F'][-8:])
#initialize the HBP calls stream sequence to 0
SEQ = 0
# Send the Call Stream
# Send 3 Voice Header Frames
for i in range(3):
pkt = b'DMRD' + bytes([SEQ]) + SDP + bytes([_slot << 7 | HEADBITS]) + STREAM_ID + (HEAD_LC[0] + SLOT_TYPE['VOICE_LC_HEAD'][:10] + BS_DATA_SYNC + SLOT_TYPE['VOICE_LC_HEAD'][-10:] + HEAD_LC[1]).tobytes() + TAIL
SEQ = (SEQ + 1) % 0x100
yield pkt
# Send each burst, six bursts per Superframe rotating through with the proper EMBED value per burst A-F
for word in _phrase:
for burst in range(0, len(word)):
print(burst)
pkt = b'DMRD' + bytes([SEQ]) + SDP + bytes([_slot << 7 | BURSTBITS[burst % 6]]) + STREAM_ID + (word[burst + 0][0] + EMBED[burst % 6] + word[burst + 0][1]).tobytes() + TAIL
SEQ = (SEQ + 1) % 0x100
yield pkt
# Send a single Voice Terminator Frame
pkt = b'DMRD' + bytes([SEQ]) + SDP + bytes([_slot << 7 | TERMBITS]) + STREAM_ID + (TERM_LC[0] + SLOT_TYPE['VOICE_LC_TERM'][:10] + BS_DATA_SYNC + SLOT_TYPE['VOICE_LC_TERM'][-10:] + TERM_LC[1]).tobytes() + TAIL
SEQ = (SEQ + 1) % 0x100
yield pkt
# Return False to indicate we're done.
return False
if __name__ == '__main__':
from time import time
speech = pkt_gen(bytes_3(3120101), bytes_3(3120), bytes_4(312000), 0, [words['all_circuits'], words['all_circuits']])
while True:
try:
pkt = next(speech)
except StopIteration:
break
print(len(pkt), pkt[4], pkt)

BIN
normal.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

View File

@ -1,169 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
# Python modules we need
import sys
from bitarray import bitarray
from time import time, sleep
from importlib import import_module
from binascii import b2a_hex as bhex
# Twisted is pretty important, so I keep it separate
from twisted.internet.protocol import Factory, Protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet import reactor, task
# Things we import from the main hblink module
from hblink import HBSYSTEM, OPENBRIDGE, systems, hblink_handler, reportFactory, REPORT_OPCODES, mk_aliases
from dmr_utils3.utils import bytes_3, bytes_4, int_id, get_alias
from dmr_utils3 import decode, bptc, const
import config
import log
from const import *
from mk_voice import pkt_gen
from voice_lib import words
# Stuff for socket reporting
import pickle
# REMOVE LATER from datetime import datetime
# The module needs logging, but handlers, etc. are controlled by the parent
import logging
logger = logging.getLogger(__name__)
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
__author__ = 'Cortney T. Buffington, N0MJS'
__copyright__ = 'Copyright (c) 2016-2019 Cortney T. Buffington, N0MJS and the K0USY Group'
__credits__ = 'Colin Durbridge, G4EML, Steve Zingman, N4IRS; Mike Zingman, N4IRR; Jonathan Naylor, G4KLX; Hans Barthen, DL5DI; Torsten Shultze, DG1HT'
__license__ = 'GNU GPLv3'
__maintainer__ = 'Cort Buffington, N0MJS'
__email__ = 'n0mjs@me.com'
# Module gobal varaibles
class OBP(OPENBRIDGE):
def __init__(self, _name, _config, _report):
OPENBRIDGE.__init__(self, _name, _config, _report)
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
pass
class HBP(HBSYSTEM):
def __init__(self, _name, _config, _report):
HBSYSTEM.__init__(self, _name, _config, _report)
self.last_stream = b'\x00'
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
if (_frame_type == HBPF_DATA_SYNC) and (_dtype_vseq == HBPF_SLT_VTERM) and (_stream_id != self.last_stream):
print(int_id(_stream_id), int_id(self.last_stream))
self.last_stream = _stream_id
print('start speech')
speech = pkt_gen(bytes_3(3120101), bytes_3(2), bytes_4(3120119), 0, [words['all_circuits'],words['all_circuits']])
sleep(1)
while True:
try:
pkt = next(speech)
except StopIteration:
break
sleep(.058)
self.send_system(pkt)
print(bhex(pkt))
print('end speech')
#************************************************
# MAIN PROGRAM LOOP STARTS HERE
#************************************************
if __name__ == '__main__':
import argparse
import sys
import os
import signal
# Change the current directory to the location of the application
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually hblink.cfg)')
parser.add_argument('-l', '--logging', action='store', dest='LOG_LEVEL', help='Override config file logging level.')
cli_args = parser.parse_args()
# Ensure we have a path for the config file, if one wasn't specified, then use the default (top of file)
if not cli_args.CONFIG_FILE:
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/hblink.cfg'
# Call the external routine to build the configuration dictionary
CONFIG = config.build_config(cli_args.CONFIG_FILE)
# Start the system logger
if cli_args.LOG_LEVEL:
CONFIG['LOGGER']['LOG_LEVEL'] = cli_args.LOG_LEVEL
logger = log.config_logging(CONFIG['LOGGER'])
logger.info('\n\nCopyright (c) 2013, 2014, 2015, 2016, 2018, 2019\n\tThe Regents of the K0USY Group. All rights reserved.\n')
logger.debug('(GLOBAL) Logging system started, anything from here on gets logged')
# Set up the signal handler
def sig_handler(_signal, _frame):
logger.info('(GLOBAL) SHUTDOWN: CONFBRIDGE IS TERMINATING WITH SIGNAL %s', str(_signal))
hblink_handler(_signal, _frame)
logger.info('(GLOBAL) SHUTDOWN: ALL SYSTEM HANDLERS EXECUTED - STOPPING REACTOR')
reactor.stop()
# Set signal handers so that we can gracefully exit if need be
for sig in [signal.SIGINT, signal.SIGTERM]:
signal.signal(sig, sig_handler)
# Create the name-number mapping dictionaries
peer_ids, subscriber_ids, talkgroup_ids = mk_aliases(CONFIG)
# INITIALIZE THE REPORTING LOOP
if CONFIG['REPORTS']['REPORT']:
report_server = config_reports(CONFIG, bridgeReportFactory)
else:
report_server = None
logger.info('(REPORT) TCP Socket reporting not configured')
# HBlink instance creation
logger.info('(GLOBAL) HBlink \'bridge.py\' -- SYSTEM STARTING...')
for system in CONFIG['SYSTEMS']:
if CONFIG['SYSTEMS'][system]['ENABLED']:
if CONFIG['SYSTEMS'][system]['MODE'] == 'OPENBRIDGE':
systems[system] = OBP(system, CONFIG, report_server)
else:
systems[system] = HBP(system, CONFIG, report_server)
reactor.listenUDP(CONFIG['SYSTEMS'][system]['PORT'], systems[system], interface=CONFIG['SYSTEMS'][system]['IP'])
logger.debug('(GLOBAL) %s instance created: %s, %s', CONFIG['SYSTEMS'][system]['MODE'], system, systems[system])
def loopingErrHandle(failure):
logger.error('(GLOBAL) STOPPING REACTOR TO AVOID MEMORY LEAK: Unhandled error in timed loop.\n %s', failure)
reactor.stop()
reactor.run()

View File

@ -1,209 +0,0 @@
# PROGRAM-WIDE PARAMETERS GO HERE
# PATH - working path for files, leave it alone unless you NEED to change it
# PING_TIME - the interval that peers will ping the master, and re-try registraion
# - how often the Master maintenance loop runs
# MAX_MISSED - how many pings are missed before we give up and re-register
# - number of times the master maintenance loop runs before de-registering a peer
#
# ACLs:
#
# Access Control Lists are a very powerful tool for administering your system.
# But they consume packet processing time. Disable them if you are not using them.
# But be aware that, as of now, the configuration stanzas still need the ACL
# sections configured even if you're not using them.
#
# REGISTRATION ACLS ARE ALWAYS USED, ONLY SUBSCRIBER AND TGID MAY BE DISABLED!!!
#
# The 'action' May be PERMIT|DENY
# Each entry may be a single radio id, or a hypenated range (e.g. 1-2999)
# Format:
# ACL = 'action:id|start-end|,id|start-end,....'
# --for example--
# SUB_ACL: DENY:1,1000-2000,4500-60000,17
#
# ACL Types:
# REG_ACL: peer radio IDs for registration (only used on HBP master systems)
# SUB_ACL: subscriber IDs for end-users
# TGID_TS1_ACL: destination talkgroup IDs on Timeslot 1
# TGID_TS2_ACL: destination talkgroup IDs on Timeslot 2
#
# ACLs may be repeated for individual systems if needed for granularity
# Global ACLs will be processed BEFORE the system level ACLs
# Packets will be matched against all ACLs, GLOBAL first. If a packet 'passes'
# All elements, processing continues. Packets are discarded at the first
# negative match, or 'reject' from an ACL element.
#
# If you do not wish to use ACLs, set them to 'PERMIT:ALL'
# TGID_TS1_ACL in the global stanza is used for OPENBRIDGE systems, since all
# traffic is passed as TS 1 between OpenBridges
[GLOBAL]
PATH: ./
PING_TIME: 5
MAX_MISSED: 3
USE_ACL: True
REG_ACL: PERMIT:ALL
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
# NOT YET WORKING: NETWORK REPORTING CONFIGURATION
# Enabling "REPORT" will configure a socket-based reporting
# system that will send the configuration and other items
# to a another process (local or remote) that may process
# the information for some useful purpose, like a web dashboard.
#
# REPORT - True to enable, False to disable
# REPORT_INTERVAL - Seconds between reports
# REPORT_PORT - TCP port to listen on if "REPORT_NETWORKS" = NETWORK
# REPORT_CLIENTS - comma separated list of IPs you will allow clients
# to connect on. Entering a * will allow all.
#
# ****FOR NOW MUST BE TRUE - USE THE LOOPBACK IF YOU DON'T USE THIS!!!****
[REPORTS]
REPORT: True
REPORT_INTERVAL: 60
REPORT_PORT: 4322
REPORT_CLIENTS: 127.0.0.1
# SYSTEM LOGGER CONFIGURAITON
# This allows the logger to be configured without chaning the individual
# python logger stuff. LOG_FILE should be a complete path/filename for *your*
# system -- use /dev/null for non-file handlers.
# LOG_HANDLERS may be any of the following, please, no spaces in the
# list if you use several:
# null
# console
# console-timed
# file
# file-timed
# syslog
# LOG_LEVEL may be any of the standard syslog logging levels, though
# as of now, DEBUG, INFO, WARNING and CRITICAL are the only ones
# used.
#
[LOGGER]
LOG_FILE: /tmp/hb-playback.log
LOG_HANDLERS: console
LOG_LEVEL: DEBUG
LOG_NAME: HBlink3 Playback
# DOWNLOAD AND IMPORT SUBSCRIBER, PEER and TGID ALIASES
# Ok, not the TGID, there's no master list I know of to download
# This is intended as a facility for other applcations built on top of
# HBlink to use, and will NOT be used in HBlink directly.
# STALE_DAYS is the number of days since the last download before we
# download again. Don't be an ass and change this to less than a few days.
[ALIASES]
TRY_DOWNLOAD: False
PATH: ./
PEER_FILE: peer_ids.json
SUBSCRIBER_FILE: subscriber_ids.json
TGID_FILE: talkgroup_ids.json
PEER_URL: https://www.radioid.net/static/rptrs.json
SUBSCRIBER_URL: https://www.radioid.net/static/users.json
STALE_DAYS: 7
# OPENBRIDGE INSTANCES - DUPLICATE SECTION FOR MULTIPLE CONNECTIONS
# OpenBridge is a protocol originall created by DMR+ for connection between an
# IPSC2 server and Brandmeister. It has been implemented here at the suggestion
# of the Brandmeister team as a way to legitimately connect HBlink to the
# Brandemiester network.
# It is recommended to name the system the ID of the Brandmeister server that
# it connects to, but is not necessary. TARGET_IP and TARGET_PORT are of the
# Brandmeister or IPSC2 server you are connecting to. PASSPHRASE is the password
# that must be agreed upon between you and the operator of the server you are
# connecting to. NETWORK_ID is a number in the format of a DMR Radio ID that
# will be sent to the other server to identify this connection.
# other parameters follow the other system types.
#
# ACLs:
# OpenBridge does not 'register', so registration ACL is meaningless.
# OpenBridge passes all traffic on TS1, so there is only 1 TGID ACL.
# Otherwise ACLs work as described in the global stanza
#[OBP-1]
#MODE: OPENBRIDGE
#ENABLED: True
#IP:
#PORT: 62035
#NETWORK_ID: 3129100
#PASSPHRASE: password
#TARGET_IP: 1.2.3.4
#TARGET_PORT: 62035
#USE_ACL: True
#SUB_ACL: DENY:1
#TGID_ACL: PERMIT:ALL
# MASTER INSTANCES - DUPLICATE SECTION FOR MULTIPLE MASTERS
# HomeBrew Protocol Master instances go here.
# IP may be left blank if there's one interface on your system.
# Port should be the port you want this master to listen on. It must be unique
# and unused by anything else.
# Repeat - if True, the master repeats traffic to peers, False, it does nothing.
#
# MAX_PEERS -- maximun number of peers that may be connect to this master
# at any given time. This is very handy if you're allowing hotspots to
# connect, or using a limited computer like a Raspberry Pi.
#
# ACLs:
# See comments in the GLOBAL stanza
[MASTER]
MODE: MASTER
ENABLED: True
REPEAT: True
MAX_PEERS: 1
EXPORT_AMBE: False
IP:
PORT: 54072
PASSPHRASE: passw0rd
GROUP_HANGTIME: 5
USE_ACL: True
REG_ACL: DENY:1
SUB_ACL: DENY:1
TGID_TS1_ACL: PERMIT:ALL
TGID_TS2_ACL: PERMIT:ALL
# PEER INSTANCES - DUPLICATE SECTION FOR MULTIPLE PEERS
# There are a LOT of errors in the HB Protocol specifications on this one!
# MOST of these items are just strings and will be properly dealt with by the program
# The TX & RX Frequencies are 9-digit numbers, and are the frequency in Hz.
# Latitude is an 8-digit unsigned floating point number.
# Longitude is a 9-digit signed floating point number.
# Height is in meters
# Setting Loose to True relaxes the validation on packets received from the master.
# This will allow HBlink to connect to a non-compliant system such as XLXD, DMR+ etc.
#
# ACLs:
# See comments in the GLOBAL stanza
#[REPEATER-1]
#MODE: PEER
#ENABLED: True
#LOOSE: False
#EXPORT_AMBE: False
#IP:
#PORT: 54001
#MASTER_IP: 172.16.1.1
#MASTER_PORT: 54000
#PASSPHRASE: homebrew
#CALLSIGN: W1ABC
#RADIO_ID: 312000
#RX_FREQ: 449000000
#TX_FREQ: 444000000
#TX_POWER: 25
#COLORCODE: 1
#SLOTS: 1
#LATITUDE: 38.0000
#LONGITUDE: -095.0000
#HEIGHT: 75
#LOCATION: Anywhere, USA
#DESCRIPTION: This is a cool repeater
#URL: www.w1abc.org
#SOFTWARE_ID: 20170620
#PACKAGE_ID: MMDVM_HBlink
#GROUP_HANGTIME: 5
#OPTIONS:
#USE_ACL: True
#SUB_ACL: DENY:1
#TGID_TS1_ACL: PERMIT:ALL
#TGID_TS2_ACL: PERMIT:ALL

View File

@ -1,229 +0,0 @@
#!/usr/bin/env python
#
###############################################################################
# Copyright (C) 2016-2019 Cortney T. Buffington, N0MJS <n0mjs@me.com> (and Mike Zingman N4IRR)
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
# Python modules we need
import sys
from bitarray import bitarray
from time import time, sleep
from importlib import import_module
# Twisted is pretty important, so I keep it separate
from twisted.internet.protocol import Factory, Protocol
from twisted.protocols.basic import NetstringReceiver
from twisted.internet import reactor, task
# Things we import from the main hblink module
from hblink import HBSYSTEM, systems, hblink_handler, reportFactory, REPORT_OPCODES, config_reports, mk_aliases
from dmr_utils3.utils import bytes_3, int_id, get_alias
from dmr_utils3 import decode, bptc, const
import config
import log
import const
# The module needs logging logging, but handlers, etc. are controlled by the parent
import logging
logger = logging.getLogger(__name__)
# Does anybody read this stuff? There's a PEP somewhere that says I should do this.
__author__ = 'Cortney T. Buffington, N0MJS and Mike Zingman, N4IRR'
__copyright__ = 'Copyright (c) 2016-2019 Cortney T. Buffington, N0MJS and the K0USY Group'
__license__ = 'GNU GPLv3'
__maintainer__ = 'Cort Buffington, N0MJS'
__email__ = 'n0mjs@me.com'
__status__ = 'pre-alpha'
# Module gobal varaibles
class playback(HBSYSTEM):
def __init__(self, _name, _config, _report):
HBSYSTEM.__init__(self, _name, _config, _report)
# Status information for the system, TS1 & TS2
# 1 & 2 are "timeslot"
# In TX_EMB_LC, 2-5 are burst B-E
self.STATUS = {
1: {
'RX_START': time(),
'RX_SEQ': '\x00',
'RX_RFS': '\x00',
'TX_RFS': '\x00',
'RX_STREAM_ID': '\x00',
'TX_STREAM_ID': '\x00',
'RX_TGID': '\x00\x00\x00',
'TX_TGID': '\x00\x00\x00',
'RX_TIME': time(),
'TX_TIME': time(),
'RX_TYPE': const.HBPF_SLT_VTERM,
'RX_LC': '\x00',
'TX_H_LC': '\x00',
'TX_T_LC': '\x00',
'TX_EMB_LC': {
1: '\x00',
2: '\x00',
3: '\x00',
4: '\x00',
}
},
2: {
'RX_START': time(),
'RX_SEQ': '\x00',
'RX_RFS': '\x00',
'TX_RFS': '\x00',
'RX_STREAM_ID': '\x00',
'TX_STREAM_ID': '\x00',
'RX_TGID': '\x00\x00\x00',
'TX_TGID': '\x00\x00\x00',
'RX_TIME': time(),
'TX_TIME': time(),
'RX_TYPE': const.HBPF_SLT_VTERM,
'RX_LC': '\x00',
'TX_H_LC': '\x00',
'TX_T_LC': '\x00',
'TX_EMB_LC': {
1: '\x00',
2: '\x00',
3: '\x00',
4: '\x00',
}
}
}
self.CALL_DATA = []
def dmrd_received(self, _peer_id, _rf_src, _dst_id, _seq, _slot, _call_type, _frame_type, _dtype_vseq, _stream_id, _data):
pkt_time = time()
dmrpkt = _data[20:53]
_bits = _data[15]
if _call_type == 'group':
# Is this is a new call stream?
if (_stream_id != self.STATUS[_slot]['RX_STREAM_ID']):
self.STATUS['RX_START'] = pkt_time
logger.info('(%s) *START RECORDING* STREAM ID: %s SUB: %s (%s) REPEATER: %s (%s) TGID %s (%s), TS %s', \
self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot)
self.CALL_DATA.append(_data)
self.STATUS[_slot]['RX_STREAM_ID'] = _stream_id
return
# Final actions - Is this a voice terminator?
if (_frame_type == const.HBPF_DATA_SYNC) and (_dtype_vseq == const.HBPF_SLT_VTERM) and (self.STATUS[_slot]['RX_TYPE'] != const.HBPF_SLT_VTERM) and (self.CALL_DATA):
call_duration = pkt_time - self.STATUS['RX_START']
self.CALL_DATA.append(_data)
logger.info('(%s) *END RECORDING* STREAM ID: %s', self._system, int_id(_stream_id))
sleep(2)
logger.info('(%s) *START PLAYBACK* STREAM ID: %s SUB: %s (%s) REPEATER: %s (%s) TGID %s (%s), TS %s, Duration: %s', \
self._system, int_id(_stream_id), get_alias(_rf_src, subscriber_ids), int_id(_rf_src), get_alias(_peer_id, peer_ids), int_id(_peer_id), get_alias(_dst_id, talkgroup_ids), int_id(_dst_id), _slot, call_duration)
for i in self.CALL_DATA:
self.send_system(i)
#print(i)
sleep(0.06)
self.CALL_DATA = []
logger.info('(%s) *END PLAYBACK* STREAM ID: %s', self._system, int_id(_stream_id))
else:
if self.CALL_DATA:
self.CALL_DATA.append(_data)
# Mark status variables for use later
self.STATUS[_slot]['RX_RFS'] = _rf_src
self.STATUS[_slot]['RX_TYPE'] = _dtype_vseq
self.STATUS[_slot]['RX_TGID'] = _dst_id
self.STATUS[_slot]['RX_TIME'] = pkt_time
self.STATUS[_slot]['RX_STREAM_ID'] = _stream_id
#************************************************
# MAIN PROGRAM LOOP STARTS HERE
#************************************************
if __name__ == '__main__':
import argparse
import sys
import os
import signal
from dmr_utils3.utils import try_download, mk_id_dict
# Change the current directory to the location of the application
os.chdir(os.path.dirname(os.path.realpath(sys.argv[0])))
# CLI argument parser - handles picking up the config file from the command line, and sending a "help" message
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually playback.cfg)')
parser.add_argument('-l', '--logging', action='store', dest='LOG_LEVEL', help='Override config file logging level.')
cli_args = parser.parse_args()
# Ensure we have a path for the config file, if one wasn't specified, then use the default (top of file)
if not cli_args.CONFIG_FILE:
cli_args.CONFIG_FILE = os.path.dirname(os.path.abspath(__file__))+'/playback.cfg'
# Call the external routine to build the configuration dictionary
CONFIG = config.build_config(cli_args.CONFIG_FILE)
# Start the system logger
if cli_args.LOG_LEVEL:
CONFIG['LOGGER']['LOG_LEVEL'] = cli_args.LOG_LEVEL
logger = log.config_logging(CONFIG['LOGGER'])
logger.info('\n\nCopyright (c) 2013, 2014, 2015, 2016, 2018, 2019\n\tThe Founding Members of the K0USY Group. All rights reserved.\n')
logger.debug('Logging system started, anything from here on gets logged')
# Set up the signal handler
def sig_handler(_signal, _frame):
logger.info('SHUTDOWN: HBROUTER IS TERMINATING WITH SIGNAL %s', str(_signal))
hblink_handler(_signal, _frame)
logger.info('SHUTDOWN: ALL SYSTEM HANDLERS EXECUTED - STOPPING REACTOR')
reactor.stop()
# Set signal handers so that we can gracefully exit if need be
for sig in [signal.SIGTERM, signal.SIGINT]:
signal.signal(sig, sig_handler)
# ID ALIAS CREATION
# Download
if CONFIG['ALIASES']['TRY_DOWNLOAD'] == True:
# Try updating peer aliases file
result = try_download(CONFIG['ALIASES']['PATH'], CONFIG['ALIASES']['PEER_FILE'], CONFIG['ALIASES']['PEER_URL'], CONFIG['ALIASES']['STALE_TIME'])
logger.info(result)
# Try updating subscriber aliases file
result = try_download(CONFIG['ALIASES']['PATH'], CONFIG['ALIASES']['SUBSCRIBER_FILE'], CONFIG['ALIASES']['SUBSCRIBER_URL'], CONFIG['ALIASES']['STALE_TIME'])
logger.info(result)
# Create the name-number mapping dictionaries
peer_ids, subscriber_ids, talkgroup_ids = mk_aliases(CONFIG)
# INITIALIZE THE REPORTING LOOP
report_server = config_reports(CONFIG, reportFactory)
# HBlink instance creation
logger.info('HBlink \'playback.py\' (c) 2017-2019 Cort Buffington, N0MJS & Mike Zingman, N4IRR -- SYSTEM STARTING...')
for system in CONFIG['SYSTEMS']:
if CONFIG['SYSTEMS'][system]['ENABLED']:
if CONFIG['SYSTEMS'][system]['MODE'] == 'OPENBRIDGE':
logger.critical('%s FATAL: Instance is mode \'OPENBRIDGE\', \n\t\t...Which would be tragic for playback, since it carries multiple call\n\t\tstreams simultaneously. playback.py onlyl works with MMDVM-based systems', system)
sys.exit('playback.py cannot function with systems that are not MMDVM devices. System {} is configured as an OPENBRIDGE'.format(system))
else:
systems[system] = playback(system, CONFIG, report_server)
reactor.listenUDP(CONFIG['SYSTEMS'][system]['PORT'], systems[system], interface=CONFIG['SYSTEMS'][system]['IP'])
logger.debug('%s instance created: %s, %s', CONFIG['SYSTEMS'][system]['MODE'], system, systems[system])
reactor.run()

View File

@ -1,30 +0,0 @@
###############################################################################
# Copyright (C) 2018 Cortney T. Buffington, N0MJS <n0mjs@me.com>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
# Opcodes for the network-based reporting protocol
REPORT_OPCODES = {
'CONFIG_REQ': b'\x00',
'CONFIG_SND': b'\x01',
'BRIDGE_REQ': b'\x02',
'BRIDGE_SND': b'\x03',
'CONFIG_UPD': b'\x04',
'BRIDGE_UPD': b'\x05',
'LINK_EVENT': b'\x06',
'BRDG_EVENT': b'\x07',
}

View File

@ -1,10 +0,0 @@
bitstring>=3.1.5
bitarray>=0.8.1
Twisted>=16.3.0
dmr_utils3>=0.1.19
configparser>=3.0.0
aprslib>=0.6.42
pynmea2
maidenhead
flask
folium

View File

@ -1,87 +0,0 @@
'''
THIS EXAMPLE WILL NOT WORK AS IT IS - YOU MUST SPECIFY YOUR OWN VALUES!!!
This file is organized around the "Conference Bridges" that you wish to use. If you're a c-Bridge
person, think of these as "bridge groups". You might also liken them to a "reflector". If a particular
system is "ACTIVE" on a particular conference bridge, any traffid from that system will be sent
to any other system that is active on the bridge as well. This is not an "end to end" method, because
each system must independently be activated on the bridge.
The first level (e.g. "WORLDWIDE" or "STATEWIDE" in the examples) is the name of the conference
bridge. This is any arbitrary ASCII text string you want to use. Under each conference bridge
definition are the following items -- one line for each HBSystem as defined in the main HBlink
configuration file.
* SYSTEM - The name of the sytem as listed in the main hblink configuration file (e.g. hblink.cfg)
This MUST be the exact same name as in the main config file!!!
* TS - Timeslot used for matching traffic to this confernce bridge
XLX connections should *ALWAYS* use TS 2 only.
* TGID - Talkgroup ID used for matching traffic to this conference bridge
XLX connections should *ALWAYS* use TG 9 only.
* ON and OFF are LISTS of Talkgroup IDs used to trigger this system off and on. Even if you
only want one (as shown in the ON example), it has to be in list format. None can be
handled with an empty list, such as " 'ON': [] ".
* TO_TYPE is timeout type. If you want to use timers, ON means when it's turned on, it will
turn off afer the timout period and OFF means it will turn back on after the timout
period. If you don't want to use timers, set it to anything else, but 'NONE' might be
a good value for documentation!
* TIMOUT is a value in minutes for the timout timer. No, I won't make it 'seconds', so don't
ask. Timers are performance "expense".
* RESET is a list of Talkgroup IDs that, in addition to the ON and OFF lists will cause a running
timer to be reset. This is useful if you are using different TGIDs for voice traffic than
triggering. If you are not, there is NO NEED to use this feature.
'''
BRIDGES = {
## 'ENGLISH': [
## {'SYSTEM': 'CHANGE_ME-1', 'TS': 1, 'TGID': 13, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'NONE', 'ON': [3,], 'OFF': [8,10], 'RESET': []},
## {'SYSTEM': 'CHANGE_ME-2', 'TS': 1, 'TGID': 13, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'NONE', 'ON': [3,], 'OFF': [8,10], 'RESET': []},
## ],
## 'STATEWIDE': [
## {'SYSTEM': 'CHANGE_ME-1', 'TS': 2, 'TGID': 3129, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'NONE', 'ON': [4,], 'OFF': [7,10], 'RESET': []},
## {'SYSTEM': 'CHANGE_ME-2', 'TS': 2, 'TGID': 3129, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'NONE', 'ON': [4,], 'OFF': [7,10], 'RESET': []},
## ],
'ECHO': [
{'SYSTEM': 'MASTER-1', 'TS': 2, 'TGID': 9999, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'ON', 'ON': [9999,], 'OFF': [9,10], 'RESET': []},
{'SYSTEM': 'ECHO', 'TS': 2, 'TGID': 9999, 'ACTIVE': True, 'TIMEOUT': 2, 'TO_TYPE': 'ON', 'ON': [9999,], 'OFF': [9,10], 'RESET': []},
]
}
'''
list the names of each system that should bridge unit to unit (individual) calls.
'''
UNIT = ['MASTER-1', 'CHANGE_ME']
'''
Unit Call flood timeout:
The amount of time to keep sending private calls to a single system before
flooding all systems with the call. A higher value should be set for systems where subscribers
are not moving between systems often. A lower value should be set for systems that have subscribers
moving between systems often.
Time is in minutes.
'''
UNIT_TIME = 1
'''
Input the DMR ID and SYSTEM of a subscriber that you would like to have always have private calls routed.
This will not flood all systems.
'''
STATIC_UNIT = [
# [ 456, 'CLIENT-1'],
# [ 123, 'MASTER-1'],
[ 9099, 'D-APRS']
]
'''
This is for testing the syntax of the file. It won't eliminate all errors, but running this file
like it were a Python program itself will tell you if the syntax is correct!
'''
if __name__ == '__main__':
from pprint import pprint
pprint(BRIDGES)
print(UNIT)
print(STATIC_UNIT)

View File

@ -1,85 +0,0 @@
###############################################################################
# GPS/Data - Copyright (C) 2020 Eric Craw, KF7EEL <kf7eel@qsl.net>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
import aprslib
import ast, os
import re
from configparser import ConfigParser
import time
import argparse
def mailbox_write(call, dmr_id, time, message, recipient):
global mailbox_file
mail_file = ast.literal_eval(os.popen('cat ' + parser.get('GPS_DATA', 'MAILBOX_FILE')).read())
mail_file.insert(0, {'call': call, 'dmr_id': dmr_id, 'time': time, 'message':message, 'recipient': recipient})
with open(parser.get('GPS_DATA', 'MAILBOX_FILE'), 'w') as mailbox_file:
mailbox_file.write(str(mail_file[:100]))
mailbox_file.close()
print('User mail saved.')
def aprs_filter(packet):
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
if 'addresse' in aprslib.parse(packet):
#print(aprslib.parse(packet))
recipient = re.sub('-.*','', aprslib.parse(packet)['addresse'])
recipient_ssid = re.sub('.*-','', aprslib.parse(packet)['addresse'])
if recipient == '':
pass
else:
for i in user_settings.items():
ssid = i[1][1]['ssid']
if i[1][1]['ssid'] == '':
ssid = user_aprs_ssid
if recipient in i[1][0]['call'] and recipient_ssid in ssid:
mailbox_write(re.sub('-.*','', aprslib.parse(packet)['addresse']), aprslib.parse(packet)['from'], time.time(), aprslib.parse(packet)['message_text'], recipient)
if 'msgNo' in aprslib.parse(packet):
time.sleep(1)
AIS.sendall(aprslib.parse(packet)['addresse'] + '>APHBL3,TCPIP*:' + ':' + aprslib.parse(packet)['from'].ljust(9) +':ack'+aprslib.parse(packet)['msgNo'])
print('Send ACK')
print(aprslib.parse(packet)['addresse'] + '>APHBL3,TCPIP*:' + ':' + aprslib.parse(packet)['from'].ljust(9) +':ack'+aprslib.parse(packet)['msgNo'])
## else:
## print(aprslib.parse(packet)['from'])
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually gps_data.cfg)')
cli_args = arg_parser.parse_args()
parser = ConfigParser()
if not cli_args.CONFIG_FILE:
print('\n\nMust specify a config file with -c argument.\n\n')
parser.read(cli_args.CONFIG_FILE)
aprs_server = parser.get('GPS_DATA', 'APRS_SERVER')
aprs_port = parser.get('GPS_DATA', 'APRS_PORT')
aprs_login = parser.get('GPS_DATA', 'APRS_RECEIVE_LOGIN_CALL')
aprs_passcode = parser.get('GPS_DATA', 'APRS_LOGIN_PASSCODE')
mailbox_file = parser.get('GPS_DATA', 'MAILBOX_FILE')
user_settings_file = parser.get('GPS_DATA', 'USER_SETTINGS_FILE')
user_aprs_ssid = parser.get('GPS_DATA', 'USER_APRS_SSID')
AIS = aprslib.IS(aprs_login, passwd=int(aprs_passcode), host=aprs_server, port=int(aprs_port))
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
print('APRS message receive script for GPS/Data Application.\nAuthor: Eric, KF7EEL - kf7eel@qsl.net')
AIS.set_filter(parser.get('GPS_DATA', 'APRS_FILTER'))
AIS.connect()
print('Connecting to APRS-IS')
AIS.consumer(aprs_filter, raw=True)

View File

@ -1,764 +0,0 @@
###############################################################################
# HBLink - Copyright (C) 2020 Cortney T. Buffington, N0MJS <n0mjs@me.com>
# GPS/Data - Copyright (C) 2020 Eric Craw, KF7EEL <kf7eel@qsl.net>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
This is a web dashboard for the GPS/Data application.
'''
from flask import Flask, render_template, request, Response, Markup
import ast, os
#from dashboard_settings import *
import folium
from folium.plugins import MarkerCluster
import re
from datetime import datetime
import argparse
from configparser import ConfigParser
app = Flask(__name__)
tbl_hdr = '''
<table style="border-color: black; margin-left: auto; margin-right: auto;" border="2" cellspacing="6" cellpadding="2"><tbody>
'''
tbl_ftr = '''
</tbody>
</table>
'''
def get_loc_data():
try:
dash_loc = ast.literal_eval(os.popen('cat ' + loc_file).read())
tmp_loc = ''
loc_hdr = '''
<tr>
<td style="text-align: center;">
<h2><strong>&nbsp;Callsign&nbsp;</strong></h2>
</td>
<td style="text-align: center;">
<h2>&nbsp;<strong>Latitude</strong>&nbsp; </h2>
</td>
<td style="text-align: center;">
<h2>&nbsp;<strong>Longitude</strong>&nbsp;</h2>
</td>
<td style="text-align: center;">
<h2>&nbsp;<strong>Time</strong>&nbsp;</h2>
</td>
</tr>
'''
last_known_loc_list = []
display_number = 15
for e in dash_loc:
if display_number == 0:
break
else:
if e['call'] in last_known_loc_list:
pass
if e['call'] not in last_known_loc_list:
if type(e['time']) == str:
loc_time = str(e['time'])
if type(e['time']) == int or type(e['time']) == float:
loc_time = datetime.fromtimestamp(e['time']).strftime(time_format)
last_known_loc_list.append(e['call'])
display_number = display_number - 1
tmp_loc = tmp_loc + '''<tr>
<td style="text-align: center;"><a href="view_map?track=''' + e['call'] + '''"target="_blank"><strong>''' + e['call'] + '''</strong></a></td>
<td style="text-align: center;"><strong>&nbsp;''' + str(e['lat']) + '''&nbsp;</strong></td>
<td style="text-align: center;"><strong>&nbsp;''' + str(e['lon']) + '''&nbsp;</strong></td>
<td style="text-align: center;">&nbsp;''' + loc_time + '''&nbsp;</td>
</tr>'''
return str(str('<h1 style="text-align: center;">Last Known Location</h1>') + tbl_hdr + loc_hdr + tmp_loc + tbl_ftr)
except:
return str('<h1 style="text-align: center;">No data</h1>')
def get_bb_data():
try:
dash_bb = ast.literal_eval(os.popen('cat ' + bb_file).read())
tmp_bb = ''
bb_hdr = '''
<tr>
<td style="text-align: center;">
<h2><strong>&nbsp;Callsign&nbsp;</strong></h2>
</td>
<td style="text-align: center;">
<h2>&nbsp;<strong>ID</strong>&nbsp; </h2>
</td>
<td style="text-align: center;">
<h2>&nbsp;<strong>Bulletin</strong>&nbsp;</h2>
</td>
<td style="text-align: center;">
<h2>&nbsp;<strong>Time</strong>&nbsp;</h2>
</td>
</tr>
'''
display_number = 10
for e in dash_bb:
if display_number == 0:
break
else:
if type(e['time']) == str:
loc_time = str(e['time'])
if type(e['time']) == int or type(e['time']) == float:
loc_time = datetime.fromtimestamp(e['time']).strftime(time_format)
display_number = display_number - 1
tmp_bb = tmp_bb + '''<tr>
<td style="text-align: center;"><strong>&nbsp;''' + e['call'] + '''&nbsp;</strong></td>
<td style="text-align: center;">''' + str(e['dmr_id']) + '''</td>
<td style="text-align: center;"><strong>&nbsp;''' + e['bulletin'] + '''&nbsp;</strong></td>
<td style="text-align: center;">&nbsp;''' + loc_time + '''&nbsp;</td>
</tr>'''
return str('<h1 style="text-align: center;">Bulletin Board</h1>' + tbl_hdr + bb_hdr + tmp_bb + tbl_ftr)
except:
return str('<h1 style="text-align: center;">No data</h1>')
def check_emergency():
# open emergency txt
try:
sos_file = ast.literal_eval(os.popen('cat ' + emergency_sos_file).read())
if type(sos_file['time']) == str:
loc_time = str(sos_file['time'])
if type(sos_file['time']) == int or type(sos_file['time']) == float:
loc_time = datetime.fromtimestamp(sos_file['time']).strftime(time_format)
if '@NOTICE' in sos_file['message'] and '@SOS' not in sos_file['message']:
notice_header = '<span style="background-color: #ffffff; color: #008000;">NOTICE:</span>'
else:
notice_header = '<span style="background-color: #ff0000; color: #ffffff;">EMERGENCY ACTIVATION</span>'
value = Markup("""
<h1 style="text-align: center;">""" + notice_header + """</h1>
<table style="width: 441px; margin-left: auto; margin-right: auto;" border="3">
<tbody>
<tr>
<td style="width: 78.3667px;"><span style="text-decoration: underline;"><strong>From:</strong></span></td>
<td style="width: 345.633px; text-align: center;"><strong>""" + sos_file['call'] + """</strong> - """ + str(sos_file['dmr_id']) + """</td>
</tr>
<tr>
<td style="width: 78.3667px;"><span style="text-decoration: underline;"><strong>Message:</strong></span></td>
<td style="width: 345.633px; text-align: center;">""" + sos_file['message'] + """</td>
</tr>
<tr>
<td style="width: 78.3667px;"><span style="text-decoration: underline;"><strong>Time:</strong></span></td>
<td style="width: 345.633px; text-align: center;">""" + loc_time + """</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<button onclick="window.open('view_map?track=""" + sos_file['call'] + """&reload=30','_blank' );" type="button" class="emergency_button"><h1>View Station on Map</h1></button>
<p style="text-align: center;"><a href="https://aprs.fi/""" + sos_file['call'] + """"><strong>View on aprs.fi</strong></a></p>
<hr />
""")
return value
except Exception as e:
return ''
def aprs_to_latlon(x):
degrees = int(x) // 100
minutes = x - 100*degrees
return degrees + minutes/60
def user_setting_write(dmr_id, input_ssid, input_icon, input_comment):
dmr_id = int(dmr_id)
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
new_dict = user_settings
new_dict[dmr_id][1]['ssid'] = input_ssid
new_dict[dmr_id][2]['icon'] = input_icon
new_dict[dmr_id][3]['comment'] = input_comment
print(input_comment)
print(new_dict[dmr_id])
# Write modified dict to file
with open(user_settings_file, 'w') as user_dict_file:
user_dict_file.write(str(new_dict))
user_dict_file.close()
@app.route('/')
def index():
value = Markup('<strong>The HTML String</strong>')
#return get_data()
return render_template('index.html', title = dashboard_title, logo = logo, emergency = check_emergency())
@app.route('/bulletin_board')
def dash_bb():
return get_bb_data()
#return render_template('index.html', data = str(get_data()))
@app.route('/positions')
def dash_loc():
return get_loc_data()
@app.route('/help/')
def help():
#return get_data()
return render_template('help.html', title = dashboard_title, logo = logo, description = description, data_call_type = data_call_type, data_call_id = data_call_id, aprs_ssid = aprs_ssid)
@app.route('/about/')
def about():
#return get_data()
return render_template('about.html', title = dashboard_title, logo = logo, contact_name = contact_name, contact_call = contact_call, contact_email = contact_email, contact_website = contact_website)
@app.route('/view_map')
def view_map():
reload_time = request.args.get('reload')
track_call = request.args.get('track')
map_size = request.args.get('map_size')
user_loc = ast.literal_eval(os.popen('cat ' + loc_file).read())
last_known_list = []
coord_list = []
try:
if track_call:
#folium_map = folium.Map(location=map_center, zoom_start=int(zoom_level))
#marker_cluster = MarkerCluster().add_to(folium_map)
for user_coord in user_loc:
user_lat = aprs_to_latlon(float(re.sub('[A-Za-z]','', user_coord['lat'])))
user_lon = aprs_to_latlon(float(re.sub('[A-Za-z]','', user_coord['lon'])))
if type(user_coord['time']) == str:
loc_time = str(user_coord['time'])
if type(user_coord['time']) == int or type(user_coord['time']) == float:
loc_time = datetime.fromtimestamp(user_coord['time']).strftime(time_format)
if 'S' in user_coord['lat']:
user_lat = -user_lat
if 'W' in user_coord['lon']:
user_lon = -user_lon
loc_comment = ''
if 'comment' in user_coord:
loc_comment = """
<tr>
<td style="text-align: center;">Comment:</td>
</tr>
<tr>
<td style="text-align: center;"><strong>"""+ str(user_coord['comment']) +"""</strong></td>
</tr>"""
if user_coord['call'] not in last_known_list and user_coord['call'] == track_call:
folium_map = folium.Map(location=[user_lat, user_lon], tiles=map_theme, zoom_start=15)
marker_cluster = MarkerCluster().add_to(folium_map)
folium.Marker([user_lat, user_lon], popup="""<i>
<table style="width: 150px;">
<tbody>
<tr>
<td style="text-align: center;">Last Location:</td>
</tr>
<tr>
<td style="text-align: center;"><strong>"""+ str(user_coord['call']) +"""</strong></td>
</tr>
<tr>
<td style="text-align: center;"><em>"""+ loc_time +"""</em></td>
""" + loc_comment + """
</tr>
</tbody>
</table>
</i>
""", icon=folium.Icon(color="red", icon="record"), tooltip=str(user_coord['call'])).add_to(folium_map)
last_known_list.append(user_coord['call'])
if user_coord['call'] in last_known_list and user_coord['call'] == track_call:
folium.CircleMarker([user_lat, user_lon], popup="""
<table style="width: 150px;">
<tbody>
<tr>
<td style="text-align: center;"><strong>""" + user_coord['call'] + """</strong></td>
</tr>
<tr>
<td style="text-align: center;"><em>""" + loc_time + """</em></td>
</tr>
</tbody>
</table>
""", tooltip=str(user_coord['call']), fill=True, fill_color="#3186cc", radius=4).add_to(marker_cluster)
#return folium_map._repr_html_()
if not reload_time:
reload_time = 120
if not map_size:
map_view = '''<table style="width: 1000px; height: 600px; margin-left: auto; margin-right: auto;" border="1">
<tbody>
<tr>
<td>
''' + folium_map._repr_html_() + '''</td>
</tr>
</tbody>
</table>'''
if map_size == 'full':
map_view = folium_map._repr_html_()
content = '''
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="''' + str(reload_time) + """" >
<title>""" + dashboard_title + """ - Tracking """+ track_call + """</title>
</head>
<p style="text-align: center;"><strong>""" + dashboard_title + """ - Tracking """ + track_call + """</strong></p>
<p style="text-align: center;"><em>Page automatically reloads every """ + str(reload_time) + """ seconds.</em></p>
<p style="text-align: center;">
<select name="sample" onchange="location = this.value;">
<option value="view_map?track=""" + track_call + """&reload=120">2 Minutes</option>
<option value="view_map?track=""" + track_call + """&reload=">Don't Reload</option>
<option value="view_map?track=""" + track_call + """&reload=30">30 Seconds</option>
<option value="view_map?track=""" + track_call + """&reload=5">5 Minutes</option>
<option value="view_map?track=""" + track_call + """&reload=600">10 Minutes</option>
</select>
<p style="text-align: center;"><button onclick="self.close()">Close</button><!--<button onclick="history.back()">Back</button>-->
</p>
""" + map_view
return render_template('generic.html', title = dashboard_title, logo = logo, content = Markup(content))
except Exception as e:
content = """<h1 style="text-align: center;">Station not found.</h1>
#<p style="text-align: center;"><button onclick="self.close()">Close Window</button>
#</p>"""
return render_template('generic.html', title = dashboard_title, logo = logo, content = Markup(content))
if not track_call:
folium_map = folium.Map(location=(map_center_lat, map_center_lon), tiles=map_theme, zoom_start=int(zoom_level))
marker_cluster = MarkerCluster().add_to(folium_map)
for user_coord in user_loc:
user_lat = aprs_to_latlon(float(re.sub('[A-Za-z]','', user_coord['lat'])))
user_lon = aprs_to_latlon(float(re.sub('[A-Za-z]','', user_coord['lon'])))
if type(user_coord['time']) == str:
loc_time = str(user_coord['time'])
if type(user_coord['time']) == int or type(user_coord['time']) == float:
loc_time = datetime.fromtimestamp(user_coord['time']).strftime(time_format)
if 'S' in user_coord['lat']:
user_lat = -user_lat
if 'W' in user_coord['lon']:
user_lon = -user_lon
loc_comment = ''
coord_list.append([user_lat, user_lon])
if 'comment' in user_coord:
loc_comment = """
<tr>
<td style="text-align: center;">Comment:</td>
</tr>
<tr>
<td style="text-align: center;"><strong>"""+ str(user_coord['comment']) +"""</strong></td>
</tr>"""
if user_coord['call'] not in last_known_list:
folium.Marker([user_lat, user_lon], popup="""<i>
<table style="width: 150px;">
<tbody>
<tr>
<td style="text-align: center;">Last Location:</td>
</tr>
<tr>
<td style="text-align: center;"><strong>""" + user_coord['call'] + """</strong></td>
</tr>
<tr>
<td style="text-align: center;"><em>""" + loc_time + """</em></td>
</tr>
""" + loc_comment + """
<tr>
<td style="text-align: center;"><strong><A href="view_map?track=""" + user_coord['call'] + """" target="_blank">Track Station</A></strong></td>
</tr>
</tbody>
</table>
</i>""", icon=folium.Icon(color="red", icon="record"), tooltip=str(user_coord['call'])).add_to(folium_map)
last_known_list.append(user_coord['call'])
if user_coord['call'] in last_known_list:
if coord_list.count([user_lat, user_lon]) > 15:
pass
else:
folium.CircleMarker([user_lat, user_lon], popup="""
<table style="width: 150px;">
<tbody>
<tr>
<td style="text-align: center;"><strong>""" + user_coord['call'] + """</strong></td>
</tr>
<tr>
<td style="text-align: center;"><em>""" + loc_time + """</em></td>
</tr>
</tbody>
</table>
""", tooltip=str(user_coord['call']), fill=True, fill_color="#3186cc", radius=4).add_to(marker_cluster)
return folium_map._repr_html_()
@app.route('/map/')
def map():
return render_template('map.html', title = dashboard_title, logo = logo)
@app.route('/user', methods = ['GET', 'POST'])
def user_settings():
user_settings = ast.literal_eval(os.popen('cat ' + user_settings_file).read())
user_id = request.args.get('user_id')
if request.method == 'POST' and request.form.get('dmr_id'):
if int(request.form.get('dmr_id')) in user_settings:
user_id = request.form.get('dmr_id')
ssid = user_settings[int(request.form.get('dmr_id'))][1]['ssid']
icon = user_settings[int(request.form.get('dmr_id'))][2]['icon']
comment = user_settings[int(request.form.get('dmr_id'))][3]['comment']
try:
pin = user_settings[int(request.form.get('dmr_id'))][4]['pin']
if ssid == '':
ssid = aprs_ssid
if icon == '':
icon = '\['
if comment == '':
comment = default_comment + ' ' + user_id
user_result = """
Use this tool to change the stored APRS settings for your DMR ID. When a position is sent, the stored settings will be used to format the APRS packet. Leave field(s) blank for default value.
<h2 style="text-align: center;">&nbsp;Modify Settings for ID: """ + user_id + """</h2>
<form action="user" method="post">
<table style="margin-left: auto; margin-right: auto; width: 419.367px;" border="1">
<tbody>
<tr>
<td style="width: 82px;"><strong>Callsign:</strong></td>
<td style="width: 319.367px; text-align: center;"><strong>""" + str(user_settings[int(user_id)][0]['call']) + """</strong></td>
</tr>
<tr>
<td style="width: 82px;"><strong>SSID:</strong></td>
<td style="width: 319.367px; text-align: center;"><input id="ssid" name="ssid" type="text" placeholder='""" + ssid + """' /></td>
</tr>
<tr>
<td style="width: 82px;"><strong>Icon:</strong></td>
<td style="width: 319.367px; text-align: center;"><input id="icon" name="icon" type="text" placeholder='""" + icon + """' /></td>
</tr>
<tr>
<td style="width: 82px;"><strong>Comment:</strong></td>
<td style="width: 319.367px; text-align: center;"><input id="comment" name="comment" type="text" placeholder='""" + comment + """'/></td>
</tr>
<tr>
<td style="width: 82px;"><strong>DMR ID:</strong></td>
<td style="width: 319.367px; text-align: center;"><input id="dmr_id" name="dmr_id" type="text" value='""" + user_id + """'/></td>
</tr>
<tr>
<td style="width: 82px;"><strong>PIN:</strong></td>
<td style="width: 319.367px; text-align: center;"><input id="pin" name="pin" type="password" /></td>
</tr>
</tbody>
</table>
<p style="text-align: center;"><input type="submit" value="Submit" /></p>
</form>
<p>&nbsp;</p>
"""
except:
user_result = """<h2 style="text-align: center;">No PIN set for """ + str(user_settings[int(user_id)][0]['call']) + """ - """ + request.form.get('dmr_id') + """</h2>
<p style="text-align: center;"><button onclick="history.back()">Back</button>
</p>"""
if int(request.form.get('dmr_id')) not in user_settings:
user_result = """<h2 style="text-align: center;">DMR ID not found.</h2>
<p style="text-align: center;"><button onclick="history.back()">Back</button>
</p>"""
#if edit_user:
if request.method == 'POST' and request.form.get('dmr_id') and request.form.get('pin'):
if int(request.form.get('pin')) == pin:
ssid = request.form.get('ssid')
icon = request.form.get('icon')
comment = request.form.get('comment')
user_setting_write(request.form.get('dmr_id'), request.form.get('ssid'), request.form.get('icon'), request.form.get('comment'))
user_result = """<h2 style="text-align: center;">Changed settings for """ + str(user_settings[int(user_id)][0]['call']) + """ - """ + request.form.get('dmr_id') + """</h2>
<p style="text-align: center;"><button onclick="history.back()">Back</button>
</p>"""
if int(request.form.get('pin')) != pin:
user_result = """<h2 style="text-align: center;">Incorrect PIN.</h2>
<p style="text-align: center;"><button onclick="history.back()">Back</button>
</p>"""
if request.method == 'GET' and not request.args.get('user_id'):
user_result = """
Use this tool to find, check, and change the stored APRS settings for your DMR ID. When a position is sent, the stored settings will be used to format the APRS packet.
<table style="width: 600px; margin-left: auto; margin-right: auto;" border="3">
<tbody>
<tr>
<td><form action="user" method="get">
<table style="margin-left: auto; margin-right: auto;">
<tbody>
<tr style="height: 62px;">
<td style="text-align: center; height: 62px;">
<h2><strong><label for="user_id">Look up DMR ID:</label></strong></h2>
</td>
</tr>
<tr style="height: 51.1667px;">
<td style="height: 51.1667px;"><input id="user_id" name="user_id" type="text" /></td>
</tr>
<tr style="height: 27px;">
<td style="text-align: center; height: 27px;"><input type="submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</form></td>
<td><form action="user" method="post">
<table style="margin-left: auto; margin-right: auto;">
<tbody>
<tr style="height: 62px;">
<td style="text-align: center; height: 62px;">
<h2><strong><label for="dmr_id">Edit DMR ID:</label></strong></h2>
</td>
</tr>
<tr style="height: 51.1667px;">
<td style="height: 51.1667px;"><input id="dmr_id" name="dmr_id" type="text" /></td>
</tr>
<tr style="height: 27px;">
<td style="text-align: center; height: 27px;"><input type="submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</form></td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
"""
#else:
if request.method == 'GET' and request.args.get('user_id'):
try:
call = user_settings[int(user_id)][0]['call']
ssid = user_settings[int(user_id)][1]['ssid']
icon = user_settings[int(user_id)][2]['icon']
comment = user_settings[int(user_id)][3]['comment']
if ssid == '':
ssid = aprs_ssid
if icon == '':
icon = '\['
if comment == '':
comment = default_comment + ' ' + user_id
#for result in user_settings:
#return user_settings[int(user_id)][0]
#return user_id
#return user_settings
user_result = """<h2 style="text-align: center;">&nbsp;Settings for ID: """ + user_id + """</h2>
<table style="margin-left: auto; margin-right: auto; width: 419.367px;" border="1">
<tbody>
<tr>
<td style="width: 82px;"><strong>Callsign:</strong></td>
<td style="width: 319.367px; text-align: center;">""" + user_settings[int(user_id)][0]['call'] + """</td>
</tr>
<tr>
<td style="width: 82px;"><strong>SSID:</strong></td>
<td style="width: 319.367px; text-align: center;">""" + ssid + """</td>
</tr>
<tr>
<td style="width: 82px;"><strong>Icon:</strong></td>
<td style="width: 319.367px; text-align: center;">""" + icon + """</td>
</tr>
<tr>
<td style="width: 82px;"><strong>Comment:</strong></td>
<td style="width: 319.367px; text-align: center;">""" + comment + """</td>
</tr>
</tbody>
</table>
<p style="text-align: center;"><button onclick="history.back()">Back</button>
</p>
"""
except:
user_result = '''<h2 style="text-align: center;">User ID not found.</h2>
<p style="text-align: center;"><button onclick="history.back()">Back</button>
</p>'''
return render_template('generic.html', title = dashboard_title, logo = logo, content = Markup(user_result))
@app.route('/mailbox')
def mailbox():
recipient = request.args.get('recipient')
if not recipient:
mail_content = """
<p>The Mailbox is a place where users can leave messages via DMR SMS. A user can leave a message for someone else by sending a specially formatted SMS to <strong>""" + data_call_id + """</strong>.
The message recipient can then use the mailbox to check for messages. You can also check for APRS mesages addressed to your DMR radio. Enter your call sign (without APRS SSID) below to check for messages. See the <a href="help">help</a> page for more information.</p>
<form action="mailbox" method="get">
<table style="margin-left: auto; margin-right: auto;">
<tbody>
<tr style="height: 62px;">
<td style="text-align: center; height: 62px;">
<h2><strong><label for="recipient">Callsign:</label></strong></h2>
</td>
</tr>
<tr style="height: 51.1667px;">
<td style="height: 51.1667px;"><input id="recipient" name="recipient" type="text" /></td>
</tr>
<tr style="height: 27px;">
<td style="text-align: center; height: 27px;"><input type="submit" value="Submit" /></td>
</tr>
</tbody>
</table>
</form>
<p>&nbsp;</p>
"""
else:
mailbox_file = ast.literal_eval(os.popen('cat ' + the_mailbox_file).read())
mail_content = '<h2 style="text-align: center;">Messages for: ' + recipient.upper() + '''
</h2>\n<p style="text-align: center;"><button onclick="history.back()">Back</button></p>\n
<h4 style="text-align: center;"><a href="mailbox_rss?recipient=''' + recipient.upper() + '''"><em>Mailbox RSS Feed for ''' + recipient.upper() + '''</em></a><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5QIcFBAOXAevLAAAAZZJREFUSMftlbtKA0EUhj8jWhi8gaIEC29oxEoRFESLgIXYiWVSKoj6CCrBBwj6CBHNE1hEWy21ETQqiIW1wXhPo81ZOBw2apbdVPvDsDPnP8M/5zKzECJEQKivYO8DFoAYEAGKtTpQEvhW4w3IA+tAVy2F9fgEskA8COHUL8LOKAMZoMmLQF0FewcwImmNAzPANBB18b0BFoGroNLfBiyLgI2+BMwF3XgNwCrwYsQ//BBPSRPdAoeybjE+A8ClS+Sjfnf1E5A2dW4FzoxfwWvD/XWd7oAxI24jz3gVnpS7eiEpt+KvQEL5D5qal/245zFgU+pnXzMd+Zrh9/3q5l7g3CXtTs0bgWvFffn5vDa7iKcVv2K4DS8i3cAOsAuMm8h12ovqqrVL/R3upFrRKPBgHgctvm0iSynuWNnf5bf6byy5dPKe4nukhg6XU9yW2TfsJlDpNCUX27OaP8pD4WBCzQtmX381EUeAI3Xqe6m5xoHpYAezJuJkNb9Fh0tI4+SlXhpTwJBaZ+XbCcwr+6kcPESI2uAHmAijFaMnEmYAAAAASUVORK5CYII=" /></h4>
'''
for messages in mailbox_file:
if messages['recipient'] == recipient.upper():
sender = """
<tr>
<td style="width: 63px;"><strong>DMR ID:</strong></td>
<td style="width: 292.55px; text-align: center;">""" + str(messages['dmr_id']) + """</td>
</tr>
"""
if type(messages['time']) == str:
loc_time = str(messages['time'])
if type(messages['time']) == int or type(messages['time']) == float:
loc_time = datetime.fromtimestamp(messages['time']).strftime(time_format)
if type(messages['dmr_id']) == str:
sender = """
<tr>
<td style="width: 63px;"><strong>APRS Call:</strong></td>
<td style="width: 292.55px; text-align: center;">""" + str(messages['dmr_id']) + """</td>
</tr>
"""
mail_content = mail_content + """
<table style="margin-left: auto; margin-right: auto; width: 372.55px;" border="1">
<tbody>
<tr>
<td style="width: 63px;"><strong>From:</strong></td>
<td style="text-align: center; width: 292.55px;"><strong>""" + messages['call'] + """</strong></td>
</tr>
""" + sender + """
<tr>
<td style="width: 63px;"><strong>Time:</strong></td>
<td style="width: 292.55px; text-align: center;">""" + loc_time + """</td>
</tr>
<tr>
<td style="width: 63px;"><strong>Message:</strong></td>
<td style="width: 292.55px; text-align: center;"><strong>""" + messages['message'] + """</strong></td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
"""
return render_template('generic.html', title = dashboard_title, logo = logo, content = Markup(mail_content))
@app.route('/bulletin_rss.xml')
def bb_rss():
try:
dash_bb = ast.literal_eval(os.popen('cat ' + bb_file).read())
post_data = ''
rss_header = """<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>""" + dashboard_title + """ - Bulletin Board Feed</title>
<link>""" + rss_link + """</link>
<description>This is the Bulletin Board feed from """ + dashboard_title + """</description>"""
for entry in dash_bb:
if type(entry['time']) == str:
loc_time = str(entry['time'])
if type(entry['time']) == int or type(entry['time']) == float:
loc_time = datetime.fromtimestamp(entry['time']).strftime(time_format)
post_data = post_data + """
<item>
<title>""" + entry['call'] + ' - ' + str(entry['dmr_id']) + """</title>
<link>""" + rss_link + """</link>
<description>""" + entry['bulletin'] + """ - """ + loc_time + """</description>
<pubDate>""" + datetime.fromtimestamp(entry['time']).strftime('%a, %d %b %y') +"""</pubDate>
</item>
"""
return Response(rss_header + post_data + "\n</channel>\n</rss>", mimetype='text/xml')
except Exception as e:
#return str('<h1 style="text-align: center;">No data</h1>')
return str(e)
@app.route('/mailbox_rss')
def mail_rss():
mailbox_file = ast.literal_eval(os.popen('cat ' + the_mailbox_file).read())
post_data = ''
recipient = request.args.get('recipient').upper()
rss_header = """<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0">
<channel>
<title>""" + dashboard_title + """ - Mailbox Feed for """ + recipient + """</title>
<link>""" + rss_link + """</link>
<description>This is a Mailbox feed from """ + dashboard_title + """ for """ + recipient + """.</description>"""
for entry in mailbox_file:
if type(entry['time']) == str:
loc_time = str(entry['time'])
if type(entry['time']) == int or type(entry['time']) == float:
loc_time = datetime.fromtimestamp(entry['time']).strftime(time_format)
if entry['recipient'] == recipient:
post_data = post_data + """
<item>
<title>""" + entry['call'] + ' - ' + str(entry['dmr_id']) + """</title>
<link>""" + rss_link + """</link>
<description>""" + entry['message'] + """ - """ + loc_time + """</description>
<pubDate>""" + datetime.fromtimestamp(entry['time']).strftime('%a, %d %b %y') +"""</pubDate>
</item>
"""
return Response(rss_header + post_data + "\n</channel>\n</rss>", mimetype='text/xml')
if __name__ == '__main__':
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-c', '--config', action='store', dest='CONFIG_FILE', help='/full/path/to/config.file (usually gps_data.cfg)')
cli_args = arg_parser.parse_args()
parser = ConfigParser()
if not cli_args.CONFIG_FILE:
print('\n\nMust specify a config file with -c argument.\n\n')
parser.read(cli_args.CONFIG_FILE)
###### Definitions #####
# Title of the Dashboard
dashboard_title = parser.get('GPS_DATA', 'DASHBOARD_TITLE')
# Logo used on dashboard page
logo = parser.get('GPS_DATA', 'LOGO')
dash_port = int(parser.get('GPS_DATA', 'DASH_PORT'))
# IP to run server on
dash_host = parser.get('GPS_DATA', 'DASH_HOST')
#Description of dashboard to show on main page
description = parser.get('GPS_DATA', 'DESCRIPTION')
# The following will generate a help page for your users.
# Data call type
if parser.get('GPS_DATA', 'CALL_TYPE') == 'unit':
data_call_type = 'Private Call'
if parser.get('GPS_DATA', 'CALL_TYPE') == 'group':
data_call_type = 'Group Call'
if parser.get('GPS_DATA', 'CALL_TYPE') == 'both':
data_call_type = 'Private or Group Call'
# DMR ID of GPS/Data application
data_call_id = parser.get('GPS_DATA', 'DATA_DMR_ID')
# Default APRS ssid
aprs_ssid = parser.get('GPS_DATA', 'USER_APRS_SSID')
# Gateway contact info displayed on about page.
contact_name = parser.get('GPS_DATA', 'CONTACT_NAME')
contact_call = parser.get('GPS_DATA', 'CONTACT_CALL')
contact_email = parser.get('GPS_DATA', 'CONTACT_EMAIL')
contact_website = parser.get('GPS_DATA', 'CONTACT_WEBSITE')
# Center dashboard map over these coordinates
map_center_lat = float(parser.get('GPS_DATA', 'MAP_CENTER_LAT'))
map_center_lon = float(parser.get('GPS_DATA', 'MAP_CENTER_LON'))
zoom_level = int(parser.get('GPS_DATA', 'ZOOM_LEVEL'))
map_theme = parser.get('GPS_DATA', 'MAP_THEME')
# Time format for display
time_format = parser.get('GPS_DATA', 'TIME_FORMAT')
# RSS feed link, shows in the link section of each RSS item.
rss_link = parser.get('GPS_DATA', 'RSS_LINK')
# Default APRS comment for users.
default_comment = parser.get('GPS_DATA', 'USER_APRS_COMMENT')
# DO NOT MODIFY BELOW HERE.
bb_file = parser.get('GPS_DATA', 'BULLETIN_BOARD_FILE')
loc_file = parser.get('GPS_DATA', 'LOCATION_FILE')
emergency_sos_file = parser.get('GPS_DATA', 'EMERGENCY_SOS_FILE')
the_mailbox_file = parser.get('GPS_DATA', 'MAILBOX_FILE')
user_settings_file = parser.get('GPS_DATA', 'USER_SETTINGS_FILE')
########################
app.run(debug = True, port=dash_port, host=dash_host)

View File

@ -1,63 +0,0 @@
###############################################################################
# HBLink - Copyright (C) 2020 Cortney T. Buffington, N0MJS <n0mjs@me.com>
# GPS/Data - Copyright (C) 2020 Eric Craw, KF7EEL <kf7eel@qsl.net>
#
# 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, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
###############################################################################
'''
Settings for web dashboard.
'''
# Title of the Dashboard
dashboard_title = 'HBLink3 D-APRS Dashboard'
# Logo used on dashboard page
logo = 'https://raw.githubusercontent.com/kf7eel/hblink3/gps/HBlink.png'
# Port to run server
dash_port = 8092
# IP to run server on
dash_host = '127.0.0.1'
#Description of dashboard to show on main page
description = '''
Welcome to the ''' + dashboard_title + '''.
'''
# The following will generate a help page for your users.
# Data call type
data_call_type = 'Private Call'
# DMR ID of GPS/Data application
data_call_id = '9099'
# Default APRS ssid
aprs_ssid = '15'
# Gateway contact info displayed on about page.
contact_name = 'your name'
contact_call = 'N0CALL'
contact_email = 'email@example.org'
contact_website = 'https://hbl.ink'
# Time format for display
time_format = '%H:%M:%S - %m/%d/%y'
# Center dashboard map over these coordinates
map_center = (47.00, -120.00)
zoom_level = 7
# List and preview of some map themes at http://leaflet-extras.github.io/leaflet-providers/preview/
# The following are options for map themes and just work, you should use one of these: “OpenStreetMap”, “Stamen” (Terrain, Toner, and Watercolor),
map_theme = 'Stamen Toner'
# RSS feed link, shows in the link section of each RSS item.
rss_link = 'http://localhost:8092'

View File

@ -1,28 +0,0 @@
{% include 'page.html' %}
{% include 'header.html' %}
{{description}}
<p>&nbsp;</p>
<p>Contact information for this gateway.</p>
<table style="margin-left: auto; margin-right: auto;" border="black">
<tbody>
<tr>
<td><strong>Name</strong></td>
<td>{{contact_name}} </td>
</tr>
<tr>
<td><strong>Callsign</strong></td>
<td>&nbsp;{{contact_call}}</td>
</tr>
<tr>
<td><strong>E-Mail</strong></td>
<td>&nbsp;{{contact_email}}</td>
</tr>
<tr>
<td><strong>Website</strong></td>
<td>&nbsp;{{contact_website}}</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
{% include 'footer.html' %}

View File

@ -1,5 +0,0 @@
<div>
<hr />
<div style="text-align: center;">Dashboard created by KF7EEL - <a href="https://kf7eel.github.io/hblink3/">https://github.com/kf7eel/hblink3</a><br />HBLink created by N0MJS.<br /><a href="https://github.com/HBLink-org">HBLink GitHub page</a><br />This is branch: <strong>gps<strong></div>
</body>
</html>

View File

@ -1,5 +0,0 @@
{% include 'page.html' %}
{% include 'header.html' %}
{{content}}
{% include 'footer.html' %}

View File

@ -1,17 +0,0 @@
<p><img style="display: block; margin-left: auto; margin-right: auto;" src="{{logo}}" alt="Logo" width="300" height="144" /></p>
<h1 style="text-align: center;">{{title}}</h1>
<hr />
<table style="width: 500px; margin-left: auto; margin-right: auto;" border="black" cellspacing="3" cellpadding="3">
<tbody>
<tr>
<td style="text-align: center;"><button onclick="window.location.href='/';"> Dashboard Home </button></td>
<td style="text-align: center;"><button onclick="window.location.href='/map';"> Station Map </button></td>
<td style="text-align: center;"><button onclick="window.location.href='/mailbox';"> The Mailbox </button></td>
<td style="text-align: center;"><button onclick="window.location.href='/user';"> User Settings </button></td>
<td style="text-align: center;"><button onclick="window.location.href='/help';"> Dashboard Help </button></td>
<td style="text-align: center;"><button onclick="window.location.href='/about';"> Gateway Contact </button></td>
</tr>
</tbody>
</table>
<hr />

View File

@ -1,117 +0,0 @@
{% include 'page.html' %}
{% include 'header.html' %}
<h2 style="text-align: center;">Attention:</h2>
<p><span style="color: #ff0000;"><strong>Please be aware that many (if not all) DMR radios DO NOT transmit your callsign when sending a GPS position. It is your responsibility to identify your station per the regulations of your country.</strong></span></p>
<p>&nbsp;</p>
<p>{{description}}</p>
<p>Configure your radio to send GPS positions with the following settings:</p>
<table style="margin-left: auto; margin-right: auto;" border="black">
<tbody>
<tr>
<td style="text-align: center;"><strong>Data Call Type</strong></td>
<td style="text-align: center;"><strong>DMR ID</strong></td>
</tr>
<tr>
<td style="text-align: center;">&nbsp;{{data_call_type}}</td>
<td style="text-align: center;">&nbsp;{{data_call_id}}</td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p>When a position is received by this gateway, it will extract the coordinates and create an APRS position packet. This gateway will find your callsign based your radio's DMR ID. It is essential to have your information up to date with <a href="https://radioid.net/">RadioID.net</a>. A predefined APRS SSID of <strong>{{aprs_ssid}}</strong> is appended your callsign. The APRS location packet is then uploaded to APRS-IS. No setup or account creation is required beforehand. This is pretty much "plug and play."</p>
<p>For example, N0CALL has a DMR ID of 1234567. N0CALL's radio sends a position to this gateway with the call type settings above. This gateway will query the <a href="https://radioid.net/">RadioID.net</a> database for DMR ID 1234567. The result will be an APRS location packet with APRS SSID&nbsp;{{aprs_ssid}}. </p>
<p>You can change the default APRS settings for your radio via SMS.</p>
<h2 style="text-align: center;">Commands</h2>
<table style="margin-left: auto; margin-right: auto;" border="black">
<tbody>
<tr>
<td style="text-align: center;">
<h4><strong>Command</strong></h4>
</td>
<td style="text-align: center;">
<h4><strong>Description</strong></h4>
</td>
<td style="text-align: center;">
<h4><strong>Example</strong></h4>
</td>
</tr>
<tr>
<td><strong>@COM</strong></td>
<td>Change the comment of the APRS.</td>
<td><em><code>@COM This is a test comment.</code></em></td>
</tr>
<tr>
<td><strong>@ICON</strong></td>
<td>Change the icon of the APRS position. *See <a href="http://aprs.net/vm/DOS/SYMBOLS.HTM" rel="nofollow">http://aprs.net/vm/DOS/SYMBOLS.HTM</a> for icon list.</td>
<td><em><code>@ICON /p</code></em></td>
</tr>
<tr>
<td><strong>@SSID</strong></td>
<td>Change SSID of your callsign.</td>
<td><em><code>@SSID 7</code></em></td>
</tr>
<tr>
<td><strong>@PIN</strong></td>
<td>Set a PIN. This is used for changing your APRS settings ia the dashboard. You must set this for each DMR ID you wish to change via the dashboard.</td>
<td><em><code>@PIN 1234</code></em></td>
</tr>
<tr>
<td><strong>@MH</strong></td>
<td>Set you location by maidenhead grid square. Designed for radios with no GPS or that are not compatable yet.</td>
<td><em><code>@MH DN97uk</code></em></td>
</tr>
<tr>
<td><strong>@BB</strong></td>
<td>Post a bulliten to the web dashboard.</td>
<td><em><code>@BB This is a test bulletin.</code></em></td>
</tr>
<tr>
<td><strong>@[CALLSIGN W/ SSID] A-[MESSAGE]</strong></td>
<td>Send a message to another station via APRS.</td>
<td><em><code>@N0CALL-15 A-This is a test.</code></em></td>
</tr>
<tr>
<td><strong>[EMAIL ADDRESS] E-[MESSAGE]</strong></td>
<td>Send an email to an email address.</td>
<td><em><code>test@example.org E-This is a test.</code></em></td>
</tr>
<tr>
<td><strong>@[RECIPIENT CALLSIGN] M-[MESSAGE]</strong></td>
<td>Post a message to the Mailbox.</td>
<td><em>@N0CALL M-This is a test.</em></td>
</tr>
<tr>
<td><strong>@REM MAIL</strong></td>
<td>Remove all mail addressed to you.</td>
<td><em>@REM MAIL</em></td>
</tr>
<tr>
<td><strong>@SOS</strong></td>
<td>EMERGENCY activation displays a banner on the main dashboard page.</td>
<td><em>THIS IS AN EMERGENCY. @SOS</em></td>
</tr>
<tr>
<td><strong>@NOTICE</strong></td>
<td>Used to prominantly display a notice, similar to EMERGENCY activation.</td>
<td><em>@NOTICE Server going down at 1800</em></td>
</tr>
<tr>
<td><strong>@REM SOS</strong></td>
<td>Removes an EMERGENCY or notice.</td>
<td><em>@REM SOS</em></td>
</tr>
</tbody>
</table>
<p>&nbsp;</p>
<p><strong>Commands should be in upper case.</strong> Send an SMS to <strong>{{data_call_id}}</strong> as a <strong>{{data_call_type}}</strong> with the desired command followed by the value. For example, to change your icon to a dog, the command would be <code>@ICON /p</code> (see the icon table for values). Changing your SSID is as simple as <code>@SSID 7</code>, and <code>@COM Testing 123</code> will change the comment.</p>
<p>Sending <code>@BB Test</code> will result in a post to the bulletin board with the messaage of "Test".</p>
<p><strong>To remove any of the stored values, just send the appropriate command without any input.</strong> <code>@COM</code> will remove the stored comment, <code>@ICON</code> will remove the stored icon, and <code>@ICON</code> will remove the strored icon. Any position reports sent will have the default settings.</p>
<h3 style="text-align: center;">EMERGENCY Activation</h3>
<p>The EMERGENCY Activation function will display a prominant banner accross the main dashboard page. The banner contains a message, time, callsign of station, and a link to the last known location of the station. This feature is intended to be used in situations where a user is in distress. To trigger an EMERGENCY activation, simply send an SMS to <strong>{{data_call_id}}</strong> with <strong>@SOS</strong> in the message. The <strong>@SOS</strong> command can be anywhere in the message. A less intimidating banner can be displayed for testing, or other purposes, by using <strong>@NOTICE</strong>. To remove the EMERGENCY activation, simply send the <strong>@REM SOS</strong> command.</p>
<h3 style="text-align: center;">The Map</h3>
<p>This dashboard now has a built in map. The map will display the last know location of stations and some previous plots from them. You can track a station by clicking on the red pin, and selecting the <strong>Track Station</strong> link. When tracking a station, you have a few options for a refresh rate, located in a drop down menu.</p>
<h3 style="text-align: center;">The Mailbox</h3>
<p>The Mailbox is a place where users can leave messages via DMR SMS. A user can leave a message for someone else by sending a formatted SMS to <strong>{{data_call_id}}</strong>. See the table above for a syntax example of posting a message to the Mailbox. The message recipient can then use the mailbox to check for messages. Message recipients can delete all of their messages by sending the command <strong>@REM MAIL</strong>. There is no way to remove a single message, it's all or none.</p>
{% include 'footer.html' %}

View File

@ -1,49 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="120" >
<title>{{title}}</title>
<style>
body {background-color: D3D3D3;}
h1 {color: green;}
p {
padding: 10px;
margin: 20px;
}
.content {
max-width: 1200px;
min-width: 1200px;
margin: auto;
}
.emergency_button {
display: block;
width: 100%;
border: none;
background-color: ##ff0000;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
text-align: center;
}
</style>
</head>
<div class="content">
<body>
{% include 'header.html' %}
{{emergency}}
<p style="text-align: center;"><em>Page automatically reloads every 2 minutes.</em></p>
<h4 style="text-align: center;"><a href="bulletin_rss.xml"><em>Bulletin Board RSS Feed</em></a><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAB4AAAAeCAYAAAA7MK6iAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAB3RJTUUH5QIcFBAOXAevLAAAAZZJREFUSMftlbtKA0EUhj8jWhi8gaIEC29oxEoRFESLgIXYiWVSKoj6CCrBBwj6CBHNE1hEWy21ETQqiIW1wXhPo81ZOBw2apbdVPvDsDPnP8M/5zKzECJEQKivYO8DFoAYEAGKtTpQEvhW4w3IA+tAVy2F9fgEskA8COHUL8LOKAMZoMmLQF0FewcwImmNAzPANBB18b0BFoGroNLfBiyLgI2+BMwF3XgNwCrwYsQ//BBPSRPdAoeybjE+A8ClS+Sjfnf1E5A2dW4FzoxfwWvD/XWd7oAxI24jz3gVnpS7eiEpt+KvQEL5D5qal/245zFgU+pnXzMd+Zrh9/3q5l7g3CXtTs0bgWvFffn5vDa7iKcVv2K4DS8i3cAOsAuMm8h12ovqqrVL/R3upFrRKPBgHgctvm0iSynuWNnf5bf6byy5dPKe4nukhg6XU9yW2TfsJlDpNCUX27OaP8pD4WBCzQtmX381EUeAI3Xqe6m5xoHpYAezJuJkNb9Fh0tI4+SlXhpTwJBaZ+XbCcwr+6kcPESI2uAHmAijFaMnEmYAAAAASUVORK5CYII=" /></h4>
<table>
<tbody>
<tr>
<td><div><p align="center"><iframe style="border: none;" title="Bulletin Board" src="bulletin_board" width="480" height="950"></iframe></p></div></td>
<td><div>
<p align="center"><iframe style="border: none;" title="Positions Received" src="positions" width="620" height="950"></iframe></p>
</div></td>
</tr>
</tbody>
</table>
{% include 'footer.html' %}

View File

@ -1,8 +0,0 @@
{% include 'page.html' %}
{% include 'header.html' %}
<p style="text-align: center;"><span style="color: #ff0000;"><strong>Red</strong></span>: Last location received. <span style="color: #0000ff;"><strong>Blue</strong></span>: Location history.</p>
<p style="text-align: center;">&nbsp;</p>
<div><p align="center"><iframe style="border: none;" title="Map" src="/view_map?track=" width="1100" height="700"></iframe></p></div>
<p>&nbsp;</p>
{% include 'footer.html' %}

View File

@ -1,22 +0,0 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
<style>
body {background-color: D3D3D3;}
h1 {color: green;}
p {
padding: 10px;
margin: 20px;
}
.content {
max-width: 1200px;
min-width: 1200px;
margin: auto;
}
</style>
</head>
<div class="content">
<body>

View File

@ -1,146 +0,0 @@
from bitarray import bitarray
words = {
'all_circuits': [
[bitarray('001011000001010000100010001001011111101010110000110001100010011001011000001010010000000100000111010000111101'), bitarray('100101001000101100110100111010010101011010110100001001100010000001111001101000010010000101110010111000101011')],
[bitarray('000010010000010101100110000100000010111101001010001111000010001100111011001111010110010000100100110101000111'), bitarray('001000001000100101100010010100100010001111010110011111000110001100100111000110100100110111100011001010011000')],
[bitarray('111111110010101010101001111000111010110110011010011000001001110011011101001110000011001101111010100001111111'), bitarray('010101101001110001010011011000111111000011000011011100000011011001011011100111110010111001100001000000111111')],
[bitarray('001010110011001000100111010100101001100101101010101000100101110110000001010111110001111001000110000000101110'), bitarray('000010110010010111110111111100101110001010100010101101000101000010100111000101001101111000001011010000000011')],
[bitarray('010011010001100000101011110101010011011001101000011100101010001100110110000010100111111001101000101000000010'), bitarray('011011111110101000011001100000000111000011101001010110101000010101111000101110101010001101100001100111010000')],
[bitarray('011111010010011100111010111110010110101001101100100010110000011000101011000111000100001001011000000100111111'), bitarray('000010010011100011001101101101101111000110000101101001000110001000111000111010101111001011111111111000000000')],
[bitarray('010111101111010000000011000001101100111111000101011011001011101001100010001010111010000100000001011100111010'), bitarray('011110001000001110000010111101001111000011111100110100100110011001111100110100101100011100110001101000111111')],
[bitarray('010010011010101100000110011100101011010100000111001101001110100001110101001111001111101000100101001101110110'), bitarray('000110000010000010011011111011101001111100110000000100000000000001000110011110101011100011010001110111100111')],
[bitarray('111001100001010000001010100000000101001011011111000111111111011110001001010110111100000101111001101101001001'), bitarray('011000101100011110011101100100110111000011110001101001111001001001111100111110101010101100101111001011000000')],
[bitarray('011011010000111000010110001000101100101001101011111110111110010000100111010010110110000101100011001100101001'), bitarray('111001100010011101110111100100111110000010000001001100000111001001011001101001001011101100010011111111000001')],
[bitarray('011110110101001101000000010100001011101000010001001101010010101100111010010110010111100001000101101001000111'), bitarray('111011000111011011010010010011001110010110110000111001101010000111110011101001100010011010000010101110101101')],
[bitarray('011010011101000101101000101001111000000101101010010111011001110001010001000010110101100000011011100101111011'), bitarray('000110111010011111001001010111001011011010100010101100001000011110111111110100000111101100010101010100100111')],
[bitarray('001110101010000100000001000000011111011110111011011111000111100100011011010110101101001001000111001101011101'), bitarray('001110000011100011000100110111000111011111001001110100000010010001001010010010101111010101111000011011111011')],
[bitarray('001011101111111001000100011000001101000111100010110101001110000101000110011011101001101101100001011000010100'), bitarray('010010001111110111101001101101110110000010011110110001100010010000010000110011100010101011000011110000011000')],
[bitarray('010110011011111100001101010011000111110001001011000101011011011001011000000010111111010101001000011101111101'), bitarray('111111111011010100001110001101011000010011001101011100110011011101011101100010110000001111001100100000000010')],
[bitarray('001010011100101100100000000001001111101011100110010101000111010010100011011011111001110001000011001001011111'), bitarray('110000100100101001000101111111100011010011001010110001000011011101101100100101100111110000000110101110010001')],
[bitarray('010011111111100001100111110101011100111100100111110010011111101100011100110100100111000101100100100001001010'), bitarray('011011111010000010001011010111000100110001000001000001101111001010101011000011110111000011001011001100101111')],
[bitarray('111101100010001101101100011010011111011010000110000110011011010101011000111100110010010001101000000111011100'), bitarray('010000001110011111011101111010010111100001100000110001101100101000000110100111011100101000011100111011101111')],
[bitarray('101001000000100001101110111000101111000001110100110011000011100101011010110101100101111000001010111001110010'), bitarray('110110000100001101011000100000100100101001000111101101010100111000110000111101100000001010011000101010110111')],
[bitarray('111100100010111001101111111011110110000010101100010000011000011100100100110000100011110001101111110111010100'), bitarray('001010001110010000011011011101000100110100110000111101001110111111010110001010001110010000011010001100010111')],
[bitarray('101000100110111100101001110110110110010010000110110001011101000111011001101100010100111100001000110111110110'), bitarray('011011100101111000011101000111011001101101110110100100101100111111110001010001001111110100011000100100100011')],
[bitarray('100001110100101011110100010100010001011000110100100000010100001100010111101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'0': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('000110011010000101000001001001011010110001000001101010011000001000010110001010101000001000100011000100111011'), bitarray('000010011011001111010000100100001011010111001000110100100001010000011101011010001110001001011101001111101010')],
[bitarray('000011001010101101111101010101011010011001001101010111001010011100011011000011101100110101001101001111111111'), bitarray('010101110001100010000111110110011010100100100101001100001110011010110110100110001110100000100011110010001110')],
[bitarray('101000100011010100101101011100100010101111100100000000001110010101001001110101010110000001001110001101110000'), bitarray('111101110100110000001110100000001101110100110110101000001010010010100000101101000110110011101011110110110111')],
[bitarray('111001100111111001000000101011000111000011001100111011011001100111110001111001100000100001100010101001110001'), bitarray('000111100111011011010101001100100001111101110010100001000010111101000100001111000000010111000001000101100100')],
[bitarray('111000100001110101010101111100000101010000001000010010010101100110101111111001000100111101101001110100100010'), bitarray('000100111000110101000000000100011011100001100010111000001101100001110100011101110000010000010100011110010111')],
[bitarray('101101110100101111110100001001000110010100000110100101110000010001110110111111111010110011100000010100100010'), bitarray('010010010101110100110110011100001101101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'1': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('001111101011000100000101011101000110111010111110010100001011011000100110000111001000110000000110000010100001'), bitarray('011011001111100111000111001101011000000011101000111000100011111101100100001011000110000100010011101101000011')],
[bitarray('011011001010100100100011010101110111110001000000011110010101010101011011111100010001000000100000000001100011'), bitarray('001010101101100011110000111010000001111000100010001100100001001001010100011010101000101011010001101010110111')],
[bitarray('111000100001001001100011001001010100111001010001010010001111000011001101101100010110000101100010100111000111'), bitarray('000011011000111100000100011100000101101101010010111000000111101011100010011010100101011011001010101001101011')],
[bitarray('100100000000100100100001100011010011010001001110001110011000001010110111110001100100110001100000100110100001'), bitarray('001111101001110110001100100110000101100101000101101100101101111110110111011001101000100001011110111001110011')],
[bitarray('111100010001110001101110110111110110000011001100010000001100010001000110110100111101010001101011100010000000'), bitarray('000001100000100000001001111000010111010011001100111110100110011100110101011101010011110110010000110001110000')],
[bitarray('110011101011111011100000011100000000011010100111111100010110011101001101110010001001100011000101011101100010'), bitarray('011000111100100101100010101111000101110010011000100011000100011101100010011000111100100101100010101011000101')],
[bitarray('110010011000100011000100011101100010011000111100100101100010101011000101101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'2': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('110000000100010000000111110101100001000011101100110101111000111100111111100000100000100000001000101001000000'), bitarray('001110101010000000010101110101101110100100100011100101101010111000010010101101010010100100111111010001100101')],
[bitarray('110000100001111001001101100111000110000110111110010100011100000001010011100000100110110000001010101110110110'), bitarray('011111010100110100001000001011011110101100011000010000001101110010100110010000111110010000011101111110001111')],
[bitarray('101000100010011101001000110110000111000000000011000110010000001001011011111100010101010111010101011101000100'), bitarray('011100010001100010011011100010110010110110011000100011000100011101100010011000111101101001000010101011110100')],
[bitarray('111110011010100011100100011101000010010000011100100001100010111011110100110110011000100011000100011101100010'), bitarray('011000101101100001100010100011110110101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'3': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('010010100001100001000010001101011011001000111110001111000001000111100011010011101110011001000010011100101110'), bitarray('000101101010111011000011011101101111000111011100111101100110011000001100001010100110101000011000000101110010')],
[bitarray('010010101010100100100101011001111111011100100101010000101101101100100110010010101000100000100110010101011100'), bitarray('010100110111010000111110111100110011101101010100011100100010000001000101101110000101101011011010111111111010')],
[bitarray('101000100000010100000000111100100100110101001101101100010100011110101010101000000011011100000010111100010101'), bitarray('110101001100101100000001000110011010100101100101101100100111111000000101001011011011110011100110011110101010')],
[bitarray('100000000110111000111111010001110111001011011001011010011001100110000111111100000001110101011001010001010110'), bitarray('001010100001110010011110110000011110100000100111111100011100011001000101001011001011010010011100101111100110')],
[bitarray('111100010010111101001001000101110110000110000111100011011000100100001110100100101001010000101110111011110000'), bitarray('000001101111010100011100110111011010111001010010101001001010101011110110011000100110000000011101111110011110')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'4': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('001111001110110001100001110011011110000111111111011111011001101000001110010011001010111000000110111111111100'), bitarray('011110010000100110001110101111010010100000010010001000001101000001101001001100001010000111000111001110101111')],
[bitarray('111000110110000101001001011001111001010001000000101010000100001100000011101100100110010100101101001111001101'), bitarray('011000000100110010001011101001011001110000010010000001001010010111110111110010100100001000000101110000000110')],
[bitarray('101001110011100101001010011010001100011000001110000001000110011100000011100001010000110001101000000011000101'), bitarray('101011100010001110011001011010110000111101110110111000001110011011100000111110101100110011011001001000101001')],
[bitarray('101000110011100101101111010011000000101000101110001011011100110000011011100100110000101101101110010011000010'), bitarray('101000001100010011111010111000011011101100010100110001101110000000000011110100100000100111000101010010011100')],
[bitarray('111100100101101001101111110100000110010010000011100000010000101011100010101001010011110000001101101000110010'), bitarray('010101110011000001010101011011000000101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'5': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('000110011110101101100001011101001101000100011001100100001011111010011010001011101000100101101110000101011111'), bitarray('010101111111000011111000001100011000100100000011001100101100001000001101011101111011010011110101010011001011')],
[bitarray('101000000000000000101101000000011100010000011101001111000110001110101011100001110001010000000111111100101000'), bitarray('010100111111101111011011110110000111111001000111011101000001111100001001011001110101011011001111100100011010')],
[bitarray('111100110111010001011000011101010010101010111010100101111001000010000110100000010100110101111111010000000000'), bitarray('101001110101111011000101000011111001100100000000101001101011100000000101110000010111100100011001010001000111')],
[bitarray('101000110000101100001011100000010110001111101010010000010000110001001011101100000100110001101011111011110011'), bitarray('111000011100000100010011111010110100101100110100101101101000111110101011011010100110011011111000101100000011')],
[bitarray('110101110010110111100011001100001111011000101101110010110101101000110100110100111010110110100011011000100101'), bitarray('100001000101110011010100100111001000011100010011101111110000011110000111000001001000100011011000101010001110')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'6': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('111000010110100001101000010011100011000111101011011111110101000111001110110000110101010111100111010100010101'), bitarray('001101100101110011011110111111110110101100010000010001111011111110100010000101000000001110110010010000011100')],
[bitarray('100101110110100000101101111011100100001101001000100101111010101100110100111111001000011010100100110100111101'), bitarray('111110101111011111111011001110110100001011110011100110001010101101111110101001100010111010001111011001101111')],
[bitarray('110101011001100010000111000100110000101011101100100011000110010000100110100111111000010010100101001101010001'), bitarray('101110100000010110100100100000001101100010110001001110000111001101010100000011111110101001010001001101111000')],
[bitarray('111101001010101010100100010100100111100010101100110111110010011000110110100100011110111111000111001101000011'), bitarray('110100101111011010000001110101110010111011110011111010100101010000110001011011001011101011101001100111101011')],
[bitarray('101110110111100111000101001001010111010000001000010110111010011010011010111110010011101110100000000000110011'), bitarray('001000100101110010111111011100110100111010101010101011100111011101100110000100111100110101010000101010010000')],
[bitarray('110001010011010011011001011000100101010001000110000101011010000000010000001100010101011011101000111000100100'), bitarray('000001100010101001010100001010100100110011001000111111000010011101000100010111110001110000100100011000001001')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'7': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('010010110001100100000010000100111111101010100000111011011001111010001000010110111100000100000100001101101100'), bitarray('101100001111000010001011011111001101011111011000111101100000010001101111111001010111100000000110111110100010')],
[bitarray('000110011010110001011000011101001101011110100101000110111000101111000000100101010011000101111001011001000001'), bitarray('000111000111100101010110011110101011111101010101000000011101001001110011000010001100001100000000010001000011')],
[bitarray('110100000000001100100000001101000000000010011111100011010011110011000011100000110101000101100101001101100111'), bitarray('001111100111011010010000100000011011111000100001001000000011000101010000010110001011111011010011110111000011')],
[bitarray('110001010101111001100010101010000000001011011101111110001110101010110010100101000010110000000100100010100011'), bitarray('000010100110010111101011101001101111110101010110110101100000101011010010001011011001111010011101100110100111')],
[bitarray('101101010010111100100111100111000110001110110100001010011100101101111011100100110011101000100000100110000110'), bitarray('011000101110010110011000011011110011100001010111100000001110111010110101010100101100110001001100101000010100')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'8': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('110000011010100110100000001001001110000010011000100100001000110100111111101000110100101011101100101101101001'), bitarray('111111001100011110100011111011001101101011100011001111000010011001101110011100010000010011010101010101011010')],
[bitarray('110011110101011110000101000101100101100011010100100000101111001101110111110010010101000111100010011101000101'), bitarray('000110010110010101000011001111000101101111010011011110000010011101000010001100010001100001110011100011000111')],
[bitarray('111110101011100011100100010101000100010000101101100101010000100010100001101110101101101010000011010100100110'), bitarray('001001000101010100010101100000001101101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'9': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('010010001110100101111111001101110010011110111100001000011101000110010111010110111100100001001110011101010101'), bitarray('000010101110010000011010001111000101110000100001001000100011000000100100010010001100101011000000101111110001')],
[bitarray('111100110010001100000010000000000101011110111101101111010000111111100011110000100011001000000011000001100001'), bitarray('001011101100100011000110110111000110110100110000001101000011011001110110111001100101000010001001010111011011')],
[bitarray('110100010010000000000011001001110011000011101100100011000000110111000011100100110100000101100101001101100110'), bitarray('001011100110010010010010100000001011100001000111011000101000010111110110111001010000101100010110001000100011')],
[bitarray('100101110101010100001101100100010101110001101010011111010011101000101110101000110001000100001001100110011001'), bitarray('000001010101110000010011110010010010111000110000111101001101111011000111001011001001000001001001011001000100')],
[bitarray('110001010001100001101001100011110100000100010110010100001101101110011111111000110101010011100111010100100111'), bitarray('000100000100100010011000100110010101110110001000100111000100011101000100010000111101101000110101100010110011')],
[bitarray('111110101010101111000110011101000110011001011101110001100111100011010001101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'disabled': [
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('101011001010101001000000001000000000000001000100010000001000000010000000101011001010101001000000001000000000'), bitarray('000001000100010000001000000010000000101011001010101001000000001000000000000001000100010000001000000010000000')],
[bitarray('001111000111111001000001001101111110111101100010011111001010011011101111000011110110111101100001000101011010'), bitarray('111100000010010011101000011111011100001111110101111100000011000101011100011011011100101010000011111110110011')],
[bitarray('000000100100010011111110010011100100011100001001001011100101101011101000010110111111101101011011100010110100'), bitarray('011111100001110010001110111011011110000011101001010000011011110001001101011011011110110010001111000000100101')],
[bitarray('010110111100001000111110010011101111100010001100001000100101111000110101000010101010000000010111111010011011'), bitarray('000110000101101001000001001100100001000111011010010100100100011100001101011101100000001010010111001111110101')],
[bitarray('010010001000101100000100010001001000011001100110001100011001101100010101000011101100100101100100011001010101'), bitarray('100100111111111011010101011110110001001111111000100101100010101101111110000010100111110010100010001111111111')],
[bitarray('100000100000011100000011111000000000110100001101100001100000001111111111110100110100011101000101111001110100'), bitarray('111001100110000000100111011101010001100001000001001000100110110001110001100010100111110001010111101100000001')],
[bitarray('110000100111011101100100110101100010110001000100000000000010011101010001111100110110010101100101111101000001'), bitarray('111101100110000100100011011100110001101001100101011001001011001110110101001111011000000100101101110100001011')],
[bitarray('100100110100000100101001111100010111111111010011001011110010010111000001110100110000110001001111101010010010'), bitarray('000010111010000101011100001101000001100101100111100111110101010001010111000001100000101000010101011101110110')],
[bitarray('101001110110101010000100000000110001100110001110000001111001110101011100100101100000011010111010101100011001'), bitarray('100010100000110101101001011111110010100110111001001011000000001100010111001011110000110110111100110010011111')],
[bitarray('110111111101011110100011010001010001000001110000001011101001000010001101110110101010101011100110011101000010'), bitarray('001101101001110101010001101111000001101011001010101001000000001000000000000001000100010000001000000010000000')]
],
'enabled': [
[bitarray('010011101100010000101011000011111110110001110110001001110101000111111001011010001100000001100011101111001101'), bitarray('001111101111000000110100010110011101010111011000111001100000000001001010110001100110110000100001110110100010')],
[bitarray('011010101011101100000111011001011010010101000101001000001101111001110101010010001000101000000111011101101001'), bitarray('011000010100001000001001110101000100110001000111001101000110001011100100100010000000111010000001001111010001')],
[bitarray('100000000010010100100000110000010011111001001100101000000101011111011101100101110100010100000011001101000011'), bitarray('101111010101101110001001100111111111111101010110001101000000101101110110101010011000011100000101101111111101')],
[bitarray('100001100111101100000111111000100000000010001011101011000111010110111111110000100000101100000100111001101101'), bitarray('010001001010111000000111001101110111101001000111100100000100110000000011000111111000101010000001011110011101')],
[bitarray('110100110000111000100101101001100100101010010010111011011001010110110011111100110100100101101000011011100000'), bitarray('001010011110000010110001000111011100110101100111110001001111011011100100000000000100011011010111110000100010')],
[bitarray('100000110100001001101101011110010011010000100010011100111111011010100011110101010110001111000011011100010111'), bitarray('011011101100111011011011010101011011000001001100101011101100001101111010111011111100010101100111001001110110')],
[bitarray('110101101110001110100111011001110010011011000000110100010011101010001000101101011011001100101001110010110010'), bitarray('010010000000010001111001001001100010101011001010101001000000001000000000000001000100010000001000000010000000')]
]
}