Michal Fratczak 2021-06-10 11:42:10 +02:00
commit 60a45b4d38
121 zmienionych plików z 17494 dodań i 0 usunięć

20
.gitignore vendored 100644
Wyświetl plik

@ -0,0 +1,20 @@
*.pyc
*.vscode
build
cacert.pem
privkey.pem
data_server/code/*.txt
data_server/code/*.db
data_server/code/*.txt*
data_server/code/pred
data_server/code/cusfpredict
data_server/code/basic_example.py
webUI/code/habdec_gui
webUI/code/js/test.html
webUI/code/osm
webUI/code/osm/*
data_server/code/test_car.py
data_server/code/bottle_sslify.py
habboy_data/code/habboy_data.db

674
LICENSE 100644
Wyświetl plik

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://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 <https://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
<https://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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

50
README.md 100644
Wyświetl plik

@ -0,0 +1,50 @@
![HabBoy_Radio](./docs/HabBoy_Habdec.jpg)
![HabBoy_Map](./docs/HabBoy_Osm.jpg)
# HABBOY
HabBoy is a linux/webApp to help observe and chase after High Altitude Balloons. (https://ukhas.org.uk/)
https://www.youtube.com/watch?v=ZuoNf171e_A
https://twitter.com/froszu/status/1274308780923269120
https://twitter.com/froszu/status/1271166163993661440
## Features
* server backend for linux, python3 and SQLite
* web browser GUI - run it on any device (tablet,smartphone,desktop...)
* optimized for use in a car (large buttons, simple operation, 100% offline)
* read balloon telemetry from [HabDec](https://github.com/ogre/habdec/), [Habitat](https://habitat.habhub.org/), [dl-fldigi](https://ukhas.org.uk/projects:dl-fldigi)
* display Balloon position and landspot prediction on OpenStreetMap (offline vector tiles)
* display Balloon position on GoogleMaps (requires internet connection)
* display Balloons telemetry as graphs and gauges (HighCharts.js)
## Project Status
HabBoy is an experimental software, which means no guarantees are made. To make it run you probably need some code tinkering to adjust to your needs. Also, the installation is not an automatic process - you need to generate OSM vector tiles, install Apache (or other web server) and compile/install wind prediction software.
That being said, it was used in 3 HAB missions and performed very well.
It was developed and tested on SBCs like RaspberryPI(raspiOS) and OdroidXU4(Ubuntu 18.04).
For GPS location you need an USB receiver like this one: https://www.hardkernel.com/shop/usb-gps-module/
## Structure Overview
HabBoy is a multi component software:
![alt text](./docs/habboy_structure.png)
### Components
* [data server](./data_server/README.md)
* [web browser UI](./webUI/README.md)
* [OpenStreetMap](./docs/VECTOR_TILES.md)
* [HabDec](https://github.com/ogre/habdec/)
* [fldigi bridge](./bridge/fldigi/README.md)
### discovery
* helper system to find HABBOY/HabDec in LAN without DNS and static IPs
### Now Defunct Components - this is unmaintained and depreciated
* [hw_iface](./hw_iface/README.md) - websocket interface to any external hardware (ie. arduino)
* [arduino](./arduino/README.md) - arduino code to read GPS data from uBLOX module

Wyświetl plik

@ -0,0 +1,3 @@
Arduino program to read GPS data and print it to serial.
This will be read over serial port by rPI/odroid/whatever and served with hw_iface websocket server to webUI.

Wyświetl plik

@ -0,0 +1,60 @@
#include "helpers/gps.h"
#include "helpers/rotary_mod16.h"
void setup()
{
// Serial.begin(115200);
Serial.begin(9600);
while (!Serial)
; //Wait for user to open terminal
Serial.println(F("interrupts()"));
interrupts();
Serial.println(F("Wire.begin()"));
Wire.begin();
Serial.println(F("SetupUBlox()"));
bool gps_ok = SetupUBlox();
while(!gps_ok)
{
Serial.println(F("err::gps"));
delay(1000);
}
Serial.println(F("SetupMod16RotSwitch()"));
SetupMod16RotSwitch(11, 12, 0);
Serial.println(F("setup() done"));
}
long G_GPS_WAIT = 0;
long G_ROT_WAIT = 0;
void loop()
{
/*if( G_ROT_SWITCH_COUNTER && (millis()-G_GPS_WAIT)>50 )
{
{
int rot_switch_counter = G_ROT_SWITCH_COUNTER;
G_ROT_SWITCH_COUNTER = 0;
Serial.print(F("rot::")); Serial.println(rot_switch_counter/2);
G_ROT_WAIT = millis();
}
}
*/
if (millis() - G_GPS_WAIT > 300)
{
UpdateGps();
PrintGpsState();
Serial.println();
G_GPS_WAIT = millis();
}
}

Wyświetl plik

@ -0,0 +1,132 @@
#pragma once
#include <Wire.h> //Needed for I2C to GPS
// https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library
// http://librarymanager/All#SparkFun_Ublox_GPS
#include "SparkFun_Ublox_Arduino_Library.h"
SFE_UBLOX_GPS myGPS;
bool SetupUBlox()
{
Wire.begin();
if (myGPS.begin() == false) //Connect to the Ublox module using Wire port
return false;
myGPS.setI2COutput(COM_TYPE_UBX); //Set the I2C port to output UBX only (turn off NMEA noise)
myGPS.setNavigationFrequency(3); //Set output to X times a second
myGPS.setAutoPVT(true); //Tell the GPS to "send" each solution -- NONBLOCKING
return true;
}
/*
void PrintGps()
{
Serial.print(F("gps::"));
long latitude = myGPS.getLatitude();
Serial.print(F("lat="));
Serial.print(latitude);
long longitude = myGPS.getLongitude();
Serial.print(F(",lon="));
Serial.print(longitude);
// Serial.print(F(" (degrees * 10^-7)"));
long altitude = myGPS.getAltitude();
Serial.print(F(",alt="));
Serial.print(altitude);
// Serial.print(F(" (mm)"));
long altitudeMSL = myGPS.getAltitudeMSL();
Serial.print(F(",altmsl="));
Serial.print(altitudeMSL);
byte SIV = myGPS.getSIV();
Serial.print(F(",siv="));
Serial.print(SIV);
long speed = myGPS.getGroundSpeed();
Serial.print(F(",speed="));
Serial.print(speed);
// Serial.print(F(" (mm/s)"));
long heading = myGPS.getHeading();
Serial.print(F(",heading="));
Serial.print(heading);
// Serial.print(F(" (degrees * 10^-5)"));
uint32_t acu = myGPS.getPositionAccuracy();
Serial.print(F(",acu="));
Serial.print(acu);
uint8_t fixtype = myGPS.getFixType();
Serial.print(F(",fixtype="));
Serial.print(fixtype);
Serial.print(F("\n"));
}
*/
struct GPS_STATE_T
{
long latitude;
long longitude;
int16_t altitude;
int16_t altitudeMSL;
uint8_t SIV;
uint16_t speed;
uint16_t heading;
uint32_t acu;
uint8_t fixtype;
};
GPS_STATE_T G_GPS_STATE;
void UpdateGps() // this takes 500ms
{
G_GPS_STATE.latitude = myGPS.getLatitude();
G_GPS_STATE.longitude = myGPS.getLongitude();
G_GPS_STATE.altitude = myGPS.getAltitude();
G_GPS_STATE.altitudeMSL = myGPS.getAltitudeMSL();
G_GPS_STATE.SIV = myGPS.getSIV();
G_GPS_STATE.speed = myGPS.getGroundSpeed();
G_GPS_STATE.heading = myGPS.getHeading();
G_GPS_STATE.acu = myGPS.getPositionAccuracy();
G_GPS_STATE.fixtype = myGPS.getFixType();
}
void PrintGpsState()
{
Serial.print(F("gps::"));
Serial.print(F("lat="));
Serial.print(G_GPS_STATE.latitude);
Serial.print(F(",lon="));
Serial.print(G_GPS_STATE.longitude);
Serial.print(F(",alt="));
Serial.print(G_GPS_STATE.altitude);
Serial.print(F(",altmsl="));
Serial.print(G_GPS_STATE.altitudeMSL);
Serial.print(F(",siv="));
Serial.print(G_GPS_STATE.SIV);
Serial.print(F(",speed="));
Serial.print(G_GPS_STATE.speed);
Serial.print(F(",heading="));
Serial.print(G_GPS_STATE.heading);
Serial.print(F(",acu="));
Serial.print(G_GPS_STATE.acu);
Serial.print(F(",fixtype="));
Serial.print(G_GPS_STATE.fixtype);
}

Wyświetl plik

@ -0,0 +1,44 @@
#pragma once
// modulowo.com mod 16-z
// https://kamami.pl/klawiatury-przyciski/557576-przelacznik-obrotowy-dzialajacy-w-oparciu-o-enkoder.html
// https://dl.btc.pl/kamami_wa/instrukcja-mod-16z.pdf
// S1A, S1B – axis click
// S2 i S3 – right/left rotation
short G_MOD16_ROT_LEFT_PIN = 0;
short G_MOD16_ROT_RIGHT_PIN = 0;
short G_MOD16_CLICK_PIN = 0;
void RotSwitchISR2();
void RotSwitchISR3();
void SetupMod16RotSwitch(short pinLeft, short pinRight, short pinClick)
{
G_MOD16_ROT_LEFT_PIN = pinLeft;
G_MOD16_ROT_RIGHT_PIN = pinRight;
G_MOD16_CLICK_PIN = pinClick;
// pinMode(0, INPUT);
pinMode(G_MOD16_ROT_LEFT_PIN, INPUT);
pinMode(G_MOD16_ROT_RIGHT_PIN, INPUT);
// digitalWrite (2, HIGH);
// digitalWrite (3, HIGH);
attachInterrupt(digitalPinToInterrupt(2), RotSwitchISR2, CHANGE);
attachInterrupt(digitalPinToInterrupt(3), RotSwitchISR3, CHANGE);
}
volatile int G_ROT_SWITCH_COUNTER = 0;
void RotSwitchISR2()
{
G_ROT_SWITCH_COUNTER += 1;
// delayMicroseconds(1000);
}
void RotSwitchISR3()
{
G_ROT_SWITCH_COUNTER -= 1;
// delayMicroseconds(1000);
}

Wyświetl plik

@ -0,0 +1,19 @@
#! /usr/bin/python
import serial, time, sys
ser = serial.Serial(sys.argv[1], 115200)
while 1:
serial_line = ser.readline()
print(serial_line) # If using Python 2.x use: print serial_line
# Do some other work on the data
time.sleep(.333) # sleep 5 minutes
# Loop restarts once the sleep is finished
ser.close() # Only executes once the loop exits

Wyświetl plik

@ -0,0 +1,2 @@
# fldigi bridge
connect to running instance of fldigi, reads RTTY texts, scans for valid UKHAS sentence and report to HabBoy data_server

Wyświetl plik

@ -0,0 +1,184 @@
#!/bin/env python
# dl-fldigi.exe --hab --arq-server-address 127.0.0.1 --arq-server-port 7777
# fldigi.exe --arq-server-address 127.0.0.1 --arq-server-port 7777
from __future__ import print_function
import string
import socket
import select
import time
import re
import traceback
import threading
import queue
import urllib3
def crc(i_str):
def _hex(n): return hex(int(n))[2:]
i_str = str(i_str)
CRC = 0xffff
for i in xrange(len(i_str)):
CRC ^= ord(i_str[i]) << 8
for j in xrange(8):
if (CRC & 0x8000):
CRC = (CRC << 1) ^ 0x1021
else:
CRC <<= 1
result = ''
result += _hex((CRC >> 12) & 15)
result += _hex((CRC >> 8) & 15)
result += _hex((CRC >> 4) & 15)
result += _hex(CRC & 15)
return result.lower()
def make_connection(host='localhost', port='7777'):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
port = int(port)
sock.connect(( host, port ))
sock.setblocking(0)
except:
print("fldigi2habboy: make_connection failed.")
print(traceback.format_exc())
return sock
def read_from_fldigi(sock, callback = None):
timeout_in_seconds = 10
while 1:
try:
ready = select.select([sock], [], [], timeout_in_seconds)
if ready[0]:
chunk = sock.recv(4096)
if callback:
callback(chunk)
else:
print("Waiting for some fldigi data ...")
except KeyboardInterrupt:
return
except:
print(traceback.format_exc())
class UkhasSentenceScanner(object):
'''
1. push() some characters into internal buffer
2. if a valid sentence is found, run callback(sentence)
'''
def __init__(self):
self.__buff__ = ''
self.__rex__ = re.compile( r'''(.*?)\$+(.+)(\*)(\w{4})(.*)''' )
self.__sentence_callback__ = print
def set_callback(self, cb):
self.__sentence_callback__ = cb
def push(self, chars):
# print(chars, end='')
if len(self.__buff__) > 5000:
self.__buff__ = ''
self.__buff__ += chars
sentences = self.__scan__()
for s in sentences:
self.__sentence_callback__(s)
def __scan__(self):
sentences = []
for line in string.split(self.__buff__, '\n'):
mo = self.__rex__.match( string.strip(line), re.I )
if not mo:
self.__buff__ = line
continue
if len(mo.groups()) != 5:
self.__buff__ = line #sentence might be not complete yet
continue
self.__buff__ = ''
sentence_no_crc = mo.group(2)
_crc = mo.group(4)
if crc(sentence_no_crc).lower() == _crc.lower():
sentences.append( (sentence_no_crc, _crc) )
else:
print('CRC not valid', sentence_no_crc, _crc, crc(sentence_no_crc) )
return sentences
class HabBoyBridge(object):
'''
Sends sentences to HabBoy server.
usage:
hbb = HabBoyBridge(host,port)
hbb.run() # run sending thread
hbb.push(sentence) # adds sentence to internal que
'''
def __init__(self, host = 'localhost', port = 8888):
self.__host__ = str(host)
self.__port__ = int(port)
self.__sentence_que__ = queue.Queue()
self.__run__ = False #que sending thread
self.__http__ = urllib3.PoolManager()
def push(self, sentence):
self.__sentence_que__.put(sentence)
def run(self):
self.__thread__ = threading.Thread(target = self.__send_loop__)
try:
self.__run__ = True
self.__thread__.start()
except KeyboardInterrupt:
self.stop()
def stop(self):
self.__run__ = False
if self.__thread__:
self.__thread__.join()
self.__thread__ = None
def __send_loop__(self):
while self.__run__:
try:
s = self.__sentence_que__.get(block=True, timeout=.5)
is_success = self.send(s)
print("send result OK ?", is_success)
except queue.Empty:
pass
except KeyboardInterrupt:
self.stop()
return
def send(self, sentence):
_url = 'http://{}:{}'.format(self.__host__, self.__port__)
_url += "/habboy/api/v1/sentence/fldigi/" + sentence
print("Sending sentence ", sentence, ' to ', _url)
try:
r = self.__http__.request('PUT', _url, timeout=2.0)
except:
print("Failed sending to habboy")
print(traceback.format_exc())
return False
return True
def main():
print("HabBoy connection...")
hbb = HabBoyBridge('habboy', 8888)
hbb.run()
print("Scanner")
scanner = UkhasSentenceScanner()
scanner.set_callback( lambda sent_and_crc:
hbb.send( sent_and_crc[0] + '*' + sent_and_crc[1] ) )
print("fldigi connection")
con = make_connection()
print("Connected to fldigi")
print("Go !")
read_from_fldigi( con, lambda chars: scanner.push(chars) )
if __name__ == "__main__":
main()

Wyświetl plik

@ -0,0 +1,66 @@
# data_server
```data_server``` is a backend of HabBoy. It's responsibility is:
* collects telemetry from multiple HABDECs, Habitat (and others sources)
* saves telemetry to SQLITE database
* computes telemetry dynamics (change over time, etc.)
* calculate landing prediction
* get HabBoy position from USB gps receiver
* upload HabBoy position as Habitat ChaseCar
* serves data over http REST (used by webUI)
## Installation
### data_server dependencies
sudo pip3 install python-dateutil ws4py bottle cheroot setproctitle pyserial psutil urllib3
### data_server - Install As Service
sudo cp ./data_server/code/HabBoy.service /etc/systemd/system/
sudo systemctl enable HabBoy.service
sudo systemctl daemon-reload
sudo systemctl start HabBoy.service
sudo journalctl -u HabBoy.service
## Usage
### First Use
```data_server``` saves telemetry to SQLite database. Before first use, you need to initialise DB with `main.py --initDB`, this command will create a ```habboy_data.db```.
### Updating database with payloads info
```data_server``` needs to know what flights are currently available and some information about sentence structure for each flight. Use command `main.py --updateDB` to download that information from UKHAS Habitat. Only approved flights will be downloaded, and only those with RTTY payloads.
After update, you can list what payloads are saved in DB file: `main.py --dbinfo`
If you wish to test your payload before it is approved by UKHAS admins, you need to manualy edit DB file with tool like [SQLiteBrowser](https://sqlitebrowser.org/). Edit ```PayloadInfo``` table providing PayloadId, callsign and SentenceInfo as ukhas JSON string. Use existing flights as template or look into file ```data_server/code/example_payload.info.json```.
### cusf predictor installation
To use landspot prediction, you need [cusf predictor with python wrapper](https://github.com/darksidelemm/cusf_predictor_wrapper).
After successful compilation, create symlink to cusf predictor executable:
```ln -s cusfpredict habboy_sw/data_server/code/cusfpredict```
### Downloading wind data
cusf predictor needs wind data to operate.
Here is example command to download it for Poland:
```python get_wind_data.py --lat=52 --lon=21 --latdelta=10 --londelta=10 -f 24 -m 0p25_1hr -o ~/data/noaa_wind/gfs```
### IMPORTANT
Currently prediction gives incorrect results, and until this is fixed, HabBoy connects to UKHAS Habitat for landspot data (requires internet connection).
### Launching HabBoy
After updating DB with your payload info and downloading wind data, you can start data_server with command ```./main.py --payload_id 2441777fbce3ce296e079b39ddb41a4a --wind ~/data/noaa_wind/gfs```
## HTTPS vs HTTPS
```data_server``` is a REST server over HTTP. It is possible to run it in HTTPS mode with ```--https``` flag, but you need to generate self signed certificate.
`openssl req -new -x509 -days 1095 -nodes -newkey rsa:2048 -out cacert.pem -keyout privkey.pem -subj "/CN=192.168.100.53"`
Running in HTTPS mode is not recommended. It is needed only if you wish to embed external HTTPS website as one of tabs in webUI (like www.spacenear.us).
It is also needed if you would like to use GPS build in your tablet/smartphone.

Wyświetl plik

@ -0,0 +1,132 @@
#!/usr/bin/env python3
from datetime import datetime as dtime
import os
import time
import math
import random
import formatSentence
import json
import urllib3
urllib3.disable_warnings()
http = urllib3.PoolManager()
C_BLACK = "\033[1;30m"
C_RED = "\033[1;31m"
C_GREEN = "\033[1;32m"
C_BROWN = "\033[1;33m"
C_BLUE = "\033[1;34m"
C_MAGENTA = "\033[1;35m"
C_CYAN = "\033[1;36m"
C_LIGHTGREY = "\033[1;37m"
C_OFF = "\033[0m"
C_CLEAR = "\033[2K"
if os.name == 'nt':
C_BLACK=C_RED=C_GREEN=C_BROWN=C_BLUE=C_MAGENTA=C_CYAN=C_LIGHTGREY=C_OFF=C_CLEAR=''
def DummySentenceCreator(i_payloadId, i_callsign, i_sensors_info, lat=None, lon=None, alt=None):
if not DummySentenceCreator.sentence_id:
# get last ID from DB to maintain continuity
# or comment out to test for real payloads that can restart and start from 0
#DummySentenceCreator.sentence_id = G_SentencesDB.getLastSentenceId(i_payloadId)
if not DummySentenceCreator.sentence_id:
DummySentenceCreator.sentence_id = 1
sentence = i_callsign
s_id = DummySentenceCreator.sentence_id
DummySentenceCreator.sentence_id += 1
for si in i_sensors_info:
if not "sensor" in si:
continue
if si["name"] == "sentence_id":
sentence += "," + str(int(s_id))
elif si["name"] == "date":
sentence += "," + dtime.utcnow().strftime("%m%D")
elif si["name"] == "time":
sentence += "," + dtime.utcnow().strftime("%H%M%S")
elif si["name"] == "latitude":
if lat:
sentence += ",{0:.6f}".format(lat)
else:
sentence += ",{0:.6f}".format(52.0 + math.sin(0.01 * s_id) + .0001 * random.randrange(0, 100))
elif si["name"] == "longitude":
if lon:
sentence += ",{0:.6f}".format(lon)
else:
sentence += ",{0:.6f}".format(21.0 + math.cos(0.01 * s_id) + .0001 * random.randrange(0, 100))
elif si["name"] == "altitude":
if alt:
sentence += ",{}".format(int(alt))
else:
sentence += ",{}".format(int(100 + s_id * 10))
elif si["name"] == "satellites":
sentence += "," + str(random.randrange(3, 12))
else:
if si["sensor"] == "base.ascii_float":
sentence += ",{0:.2f}".format(random.random())
elif si["sensor"] == "base.ascii_int":
sentence += "," + str(random.randrange(-100, 100))
else:
sentence += "," + si["sensor"]
sentence += "*" + formatSentence.crc(sentence)
# print(C_RED, "DUMMY ", sentence, C_OFF)
return sentence
DummySentenceCreator.sentence_id = 0
if __name__ == "__main__":
while True:
time.sleep(5)
snt =DummySentenceCreator(
i_payloadId = None,
i_callsign = 'SP5WWL',
i_sensors_info = [
{
"name": "sentence_id",
"sensor": "base.ascii_int"
},
{
"name": "time",
"sensor": "base.string"
},
{
"format": "ddmm.mmmm",
"name": "latitude",
"sensor": "stdtelem.coordinate"
},
{
"format": "ddmm.mmmm",
"name": "longitude",
"sensor": "stdtelem.coordinate"
},
{
"name": "altitude",
"sensor": "base.ascii_float"
},
{
"name": "battery",
"sensor": "base.ascii_float"
},
{
"name": "satellites",
"sensor": "base.ascii_int"
},
{
"name": "telemetry",
"sensor": "base.string"
}
],
)
res = http.request('PUT', 'http://localhost:8888/habboy/api/v1/sentence/dummy/' + snt)
res = json.loads( res.data.decode("utf-8") )
print (res, snt)

Wyświetl plik

@ -0,0 +1,10 @@
[Unit]
Description=HabBoy
Wants=network-online.target
After=network-online.target
[Service]
ExecStart=/home/mfratczak/share/dev/habboy_dev/habboy_sw/data_server/code/main.py --https --host ip --dbfile /home/mfratczak/share/dev/habboy_dev/habboy_sw/data_server/code/habboy_data.db --payload_id e11
[Install]
WantedBy=multi-user.target

Wyświetl plik

@ -0,0 +1,121 @@
#!/usr/bin/env python3
import string
import time
import datetime
import threading
import urllib3
import traceback
import math
import random
import HabHubInterface
import formatSentence
def fake_sentence():
# 'CALLSIGN,25,15:41:24,44.32800,-74.14427,00491,0,0,12,30.7,0.0,0.001,20.2,958,1b*6BC9'
# CALLSIGN,3748,15:41:24,44.32800,-74.14427,00491,0,0,12,30.7,0.0,0.001,20.2,958,1b*D55E
res = ""
res += "ARY_test"
res += "," + str(fake_sentence.id)
fake_sentence.id += 1
res += "," + datetime.datetime.utcnow().strftime("%H%M%S")
res += "," + str(52.0 + math.sin(float(fake_sentence.id) / 50)) # lat
res += "," + str(21.0 + math.sin(float(fake_sentence.id) / 50)) # lon
res += "," + str(80 + int(35000.0 * math.sin(float(fake_sentence.id) / 250))) # alt
res += "," + str(300 + int(100.0 * math.sin(float(fake_sentence.id) / 250))) # elev
res += "," + str(
15.0 + 20.0 * math.sin(float(fake_sentence.id) / 250)
) # temperature_internal
res += "," + str(
-10.0 + 20.0 * math.sin(float(fake_sentence.id) / 250)
) # temperature_external
res += "," + str(1000.0 * (1.0 / (1 + 0.1 * fake_sentence.id))) # pressure
res += ",A"
# flags
res += "*" + formatSentence.crc(res)
return res
fake_sentence.id = 1
class HabHubClient(object):
"""
periodically polls habitat for specific payload telemetry
"""
interval_seconds = 15
def __init__(self, i_payload_id, i_interval_seconds = None):
self.__payload_id = i_payload_id
self.__sentence_thread = None
self.__sentence_run = False
self.__sentences_dict = {}
self.__sentence_mtx = threading.Lock()
self.__interval_seconds = i_interval_seconds or HabHubClient.interval_seconds
self.__last_connection_time = datetime.datetime.utcfromtimestamp(0)
self.__last_sentence_time = datetime.datetime.utcfromtimestamp(0)
print("Initialized HabHub client with payload_id ", i_payload_id)
def __habhub_thread_f(self):
while self.__sentence_run:
time.sleep( self.__interval_seconds )
sentences = [ HabHubInterface.getLastSentence(self.__payload_id) ]
self.__last_connection_time = datetime.datetime.utcnow()
# sentences = [fake_sentence()]
# print ("!!!!!!!!!!!!! FAKE !!!!!!!!!!!!!!!")
if not sentences:
continue
sentence = sentences[-1]
sent_id = formatSentence.sentenceToId(sentence)
if sent_id:
with self.__sentence_mtx:
if sent_id not in self.__sentences_dict:
self.__sentences_dict[sent_id] = sentence
self.__last_sentence_time = datetime.datetime.utcnow()
# print("Habitat: ", sentence)
def Start(self):
self.__sentence_run = True
self.__sentence_thread = threading.Thread(target=self.__habhub_thread_f)
self.__sentence_thread.start()
def Stop(self):
print("HabHub Client Stopping ", self.__payload_id)
self.__sentence_run = False
if self.__sentence_thread and self.__sentence_thread.is_alive():
self.__sentence_thread.join()
self.__sentence_thread = None
def GetLastSentence(self):
res = None
with self.__sentence_mtx:
if len(self.__sentences_dict):
max_id = max(self.__sentences_dict.keys())
if max_id:
res = self.__sentences_dict[max_id]
# return 'CALLSIGN,25,15:41:24,44.32800,-74.14427,00491,0,0,12,30.7,0.0,0.001,20.2,958,1b*6BC9'
# return fake_sentence()
return res
def GetLastSentenceReceiveTime(self):
with self.__sentence_mtx:
return self.__last_sentence_time
def GetLastConnectionTime(self):
return self.__last_connection_time

Wyświetl plik

@ -0,0 +1,106 @@
Flights:
[{u"doc": {u"_id": u"af21bc2ee2b36528550e62c27dda3620",
u"_rev": u"2-f9e141dbf0f896b8b683407141cf3ce9",
u"approved": True,
u"end": u"2019-02-23T23:59:59+00:00",
u"launch": {u"location": {u"altitude": 120,
u"latitude": 52.362,
u"longitude": 21.137},
u"time": u"2019-02-23T11:00:00+00:00",
u"timezone": u"Europe/London"},
u"metadata": {u"group": u"SP5WWL & SP5YAM",
u"location": u"Marki, Poland",
u"project": u"Balon z Marek"},
u"name": u"SP5WWL - 437.600MHz 75/540 7N1 RTTY & 432.500MHz APRS",
u"payloads": [u"e0ce9ad8b0d7e8b7f8deb978727f3aa7"],
u"start": u"2019-02-23T00:00:00+00:00",
u"type": u"flight"},
u"id": u"af21bc2ee2b36528550e62c27dda3620",
u"key": [1550966399, 1550880000, u"af21bc2ee2b36528550e62c27dda3620", 0],
u"value": [u"e0ce9ad8b0d7e8b7f8deb978727f3aa7"]}]
payloads:
[{u"doc": {u"_id": u"e0ce9ad8b0d7e8b7f8deb978727f3aa7",
u"_rev": u"1-976702d368c96a27a41fae3f56950ac5",
u"metadata": {u"description": u"Tracker_2"},
u"name": u"SP5WWL RTTY 437.600 75/540 7N1 APRS 432.500",
u"sentences": [{u"callsign": u"SP5WWL-b",
u"checksum": u"crc16-ccitt",
u"fields": [{u"name": u"sentence_id",
u"sensor": u"base.ascii_int"},
{u"name": u"time",
u"sensor": u"stdtelem.time"},
{u"format": u"dd.dddd",
u"name": u"latitude",
u"sensor": u"stdtelem.coordinate"},
{u"format": u"dd.dddd",
u"name": u"longitude",
u"sensor": u"stdtelem.coordinate"},
{u"name": u"altitude",
u"sensor": u"base.ascii_int"},
{u"name": u"temperature_internal",
u"sensor": u"base.ascii_int"},
{u"name": u"battery",
u"sensor": u"base.ascii_int"},
{u"name": u"satellites",
u"sensor": u"base.ascii_int"},
{u"name": u"packets_ok",
u"sensor": u"base.ascii_int"},
{u"name": u"packets_err",
u"sensor": u"base.ascii_int"},
{u"name": u"flags",
u"sensor": u"base.string"}],
u"filters": {u"post": [{u"factor": 0.01,
u"filter": u"common.numeric_scale",
u"round": 3,
u"source": u"battery",
u"type": u"normal"},
{u"filter": u"common.invalid_location_zero",
u"type": u"normal"}]},
u"protocol": u"UKHAS"}],
u"time_created": u"2019-02-20T00:40:29+01:00",
u"transmissions": [{u"baud": 75,
u"description": u"UHF",
u"encoding": u"ASCII-7",
u"frequency": 437600000,
u"mode": u"USB",
u"modulation": u"RTTY",
u"parity": u"none",
u"shift": 540,
u"stop": 1}],
u"type": u"payload_configuration"},
u"id": u"af21bc2ee2b36528550e62c27dda3620",
u"key": [1550966399, 1550880000, u"af21bc2ee2b36528550e62c27dda3620", 1],
"telemetry": [{u"callsign": u"SQ9PPT",
u"data": {u"battery": u"2.6",
u"flags": u"80",
u"packets_err": 2,
u"packets_ok": 6233,
u"satellites": 9,
u"temperature_internal": 16},
u"gps_alt": u"621",
u"gps_heading": u"",
u"gps_lat": u"50.37177",
u"gps_lon": u"19.60548",
u"gps_speed": u"",
u"gps_time": u"2019-02-23 14:28:11",
u"mission_id": u"0",
u"picture": u"",
u"position_id": u"25950359",
u"sequence": u"993",
u"server_time": u"2019-02-23 14:28:24.613321",
u"temp_inside": u"",
u"vehicle": u"SP5WWL-b"}],
u"value": {u"_id": u"e0ce9ad8b0d7e8b7f8deb978727f3aa7"}}]
telemetry:
[]

Wyświetl plik

@ -0,0 +1,296 @@
#!/usr/bin/env python3
"""
misc utility functions for habitat queries
"""
import string
import sys
import json
from time import time
from pprint import pprint
import urllib3
urllib3.disable_warnings()
http = urllib3.PoolManager()
import formatSentence
def getFlights():
_url = (
"http://habitat.habhub.org/habitat/_design/flight/_view/end_start_including_payloads?startkey=["
+ str(int(time()))
+ "]&include_docs=True"
)
flights_json = http.request("GET", _url)
flights = json.loads(flights_json.data.decode("utf-8"))["rows"]
res = [f for f in flights if f["doc"]["type"] == "flight"]
return res
def getPayloads(i_flights=None):
_url = (
"http://habitat.habhub.org/habitat/_design/flight/_view/end_start_including_payloads?startkey=["
+ str(int(time()))
+ "]&include_docs=True"
)
all_docs = http.request("GET", _url)
all_docs = json.loads(all_docs.data.decode("utf-8"))["rows"]
if not i_flights:
i_flights = getFlights()
flyingPayloadsIds = []
for f in i_flights:
flyingPayloadsIds.extend(f["doc"]["payloads"])
res = []
for f in all_docs:
if (
f["doc"]["type"] == "payload_configuration"
and f["doc"]["_id"] in flyingPayloadsIds
):
# f['telemetry'] = getTelemetry( f['doc']['sentences'][0]['callsign'] )
res.append(f)
return res
def getCallsignsForPayloadId(payload_id):
flights = getFlights()
payloads = getPayloads(flights)
for p in payloads:
if p["doc"]["_id"] == payload_id:
return p["doc"]["sentences"][0]["callsign"]
return None
"""
def getTelemetry(i_payloadName, max_positions=1 ):
data_url = "http://spacenear.us/tracker/datanew.php"
data_str = "mode=position&type=positions&format=json&max_positions=" + str(max_positions) + "&position_id=0&vehicles=" + urllib2.quote(i_payloadName)
_url = data_url + '?' + data_str
res = http.request('GET', _url)
res = json.loads(res.data.decode('utf-8'))
res = res['positions']['position']
return res
"""
def defaultSensorsInfo(i_sentence):
"""
treat all sensors as string
except: sentence_id, time, lat, lon, alt
"""
if not i_sentence:
return None
num_sensors = len(formatSentence.getData(i_sentence))
sensors_info_arr = [
{"name": "sensor_" + str(x), "sensor": "base.string"}
for x in range(num_sensors)
]
# sentence_id
sensors_info_arr[0]["name"] = "sentence_id"
sensors_info_arr[0]["sensor"] = "base.ascii_int"
# time
sensors_info_arr[1]["name"] = "time"
sensors_info_arr[1]["sensor"] = "stdtelem.time"
# lat
sensors_info_arr[2]["name"] = "latitude"
sensors_info_arr[2]["sensor"] = "stdtelem.coordinate"
# lon
sensors_info_arr[3]["name"] = "longitude"
sensors_info_arr[3]["sensor"] = "stdtelem.coordinate"
# alt
sensors_info_arr[4]["name"] = "altitude"
sensors_info_arr[4]["sensor"] = "base.ascii_float"
return sensors_info_arr
def getSentenceInfo(i_payload_id, i_sentence=None):
# print('getSentenceInfo', (i_payload_id, i_sentence))
example_output = [
{"name": "sentence_id", "sensor": "base.ascii_int"},
{"name": "time", "sensor": "stdtelem.time"},
{"name": "latitude", "sensor": "stdtelem.coordinate", "format": "dd.dddd"},
{"name": "longitude", "sensor": "stdtelem.coordinate", "format": "dd.dddd"},
{"name": "altitude", "sensor": "base.ascii_int"},
{"name": "temperature_internal", "sensor": "base.ascii_float"},
{"name": "temperature_external", "sensor": "base.ascii_float"},
{"name": "satellites", "sensor": "base.ascii_int"},
{"name": "some_float1", "sensor": "base.ascii_float"},
{"name": "some_float2", "sensor": "base.ascii_float"},
{"name": "some_float3", "sensor": "base.ascii_float"},
{"name": "some_float4", "sensor": "base.ascii_float"},
{"name": "packets_err", "sensor": "base.ascii_int"},
{"name": "flags", "sensor": "base.string"},
]
# ARY
example_output = [
{"name": "sentence_id", "sensor": "base.ascii_int"},
{"name": "time", "sensor": "stdtelem.time"},
{"name": "latitude", "sensor": "stdtelem.coordinate", "format": "dd.dddd"},
{"name": "longitude", "sensor": "stdtelem.coordinate", "format": "dd.dddd"},
{"name": "altitude", "sensor": "base.ascii_int"},
{"name": "elev", "sensor": "base.ascii_int"},
{"name": "temperature_internal", "sensor": "base.ascii_float"},
{"name": "temperature_external", "sensor": "base.ascii_float"},
{"name": "pressure", "sensor": "base.ascii_float"},
{"name": "mesg", "sensor": "base.string"},
]
# return example_output
result = None
payloads = getPayloads(getFlights())
for p in payloads:
# print("payload ", p['doc']['_id'], p['doc']['name'], i_payload_id)
# if p['doc']['_id'] == i_payload_id or p['doc']['name'] == i_payload_id:
if (
p["doc"]["_id"] == i_payload_id
or p["doc"]["sentences"][0]["callsign"] == i_payload_id
):
result = p["doc"]["sentences"][0]["fields"]
break
else:
pass
# print(p)
'''
if not result and i_sentence:
result = defaultSensorsInfo(i_sentence)
print("Building Default sensor datainfo based on sentence: " + i_sentence)
pprint(result)
return result
'''
return result
"""
def getLastSentence_faked(i_payload_name):
getLastSentence.last_id += 1
result = "CALLSIGN," + str(getLastSentence.last_id) + ",15:41:24,44.32800,-74.14427,00491,0,0,12,30.7,0.0,0.001,20.2,958,1b*6BC9"
result = formatSentence.formatSentence(result)
return ""
return result
getLastSentence_faked.last_id = 0
"""
def getLastSentence(i_payload_id):
_url = (
"http://habitat.habhub.org/habitat/_design/flight/_view/end_start_including_payloads?startkey=["
+ str(int(time()))
+ "]&include_docs=True"
)
try:
flights_json = http.request("GET", _url)
except urllib3.exceptions.MaxRetryError:
return None
flights = json.loads(flights_json.data.decode("utf-8"))["rows"]
flight_id = None
for f in flights:
if f["doc"]["type"] != "flight":
continue
if i_payload_id in f["doc"]["payloads"]:
flight_id = f["doc"]["_id"]
break
if flight_id:
try:
r = http.request(
"GET",
'http://habitat.habhub.org/habitat/_design/payload_telemetry/_view/flight_payload_time?startkey=["'
+ flight_id
+ '","'
+ i_payload_id
+ '",[]]&endkey=["'
+ flight_id
+ '","'
+ i_payload_id
+ '"]&include_docs=True&descending=True&limit=1',
)
except urllib3.exceptions.MaxRetryError:
return None
telemetry = json.loads(r.data.decode("utf-8"))["rows"]
if telemetry:
try:
telemetry = json.loads(r.data.decode("utf-8"))["rows"][-1]
last_sentence = telemetry["doc"]["data"]["_sentence"]
last_sentence = last_sentence.strip()
except KeyError:
pprint(telemetry)
return ""
print(last_sentence)
return last_sentence
return None
def uploadChaseCar(car_data):
r = None
try:
r = http.request(
"GET",
'http://spacenear.us/tracker/track.php',
fields = car_data
)
except urllib3.exceptions.MaxRetryError:
return False
if r.status != 200:
print(r.data)
return False
return True
if __name__ == "__main__":
flights = getFlights()
payloads = getPayloads(flights)
"""
print "Flights:"
pprint(flights)
print "==================================="
print "payloads:"
pprint(payloads)
print "==================================="
for p in payloads:
print "telemetry ", p['doc']['name']
pprint( getTelemetry(p['doc']['name']) )
print "==================================="
print('M6')
pprint ( getTelemetry('M6') )
print "==================================="
print( getSentenceInfo('MI6') )
"""
pprint(getSentenceInfo("5facec9731fc190ce510c9f1ee6e4bb8"))
# pprint( getLastSentence('5facec9731fc190ce510c9f1ee6e4bb8') )
# //////////////////////////////
# print( getSentenceInfo( 0, 'fro3,3,220759,52.029996,21.999550,130.0,80.0,80.0,80.0*CE7D') )

Wyświetl plik

@ -0,0 +1,153 @@
#!/usr/bin/env python3
# BASIC COMMUNICATION WITH HABDEC WEBSOCKET SERVER
#
import sys
import string
from ws4py.client.threadedclient import WebSocketClient # pip install ws4py
import struct
import time
import threading
import bisect
import traceback
import datetime
import HabHubInterface
import formatSentence
# GLOBAL VARIABLES:
#
WS = None # websocket
WS_THREAD = None
SENTENCES = []
# WEBSOCKET CLIENT
#
class HabdecClient(WebSocketClient):
def __init__(self, i_habdec_server):
if not i_habdec_server.lower().startswith('ws://'):
i_habdec_server = 'ws://' + i_habdec_server
self.habdec_server = i_habdec_server
WebSocketClient.__init__(self, self.habdec_server)
# self.__sentences_dict = {}
# self.__sentences_sorted_ids = []
self.__sentences_arr = []
self.__sentence_mtx = threading.Lock()
self.__sentence_thread = None
self.__sentence_run = False
self.__habdec_thread = None
self.__habdec_run = False
self.__habdec_connection_initialized = False
self.__last_connection_time = datetime.datetime.utcfromtimestamp(0)
self.__last_sentence_time = datetime.datetime.utcfromtimestamp(0)
def opened(self):
print("Opened Connection")
def closed(self, code, reason=None):
print("Closed down", code, reason)
def __connect(self):
if self.terminated:
WebSocketClient.__init__(self, self.habdec_server)
# while self.__sentence_run:
while self.__habdec_run:
try:
print("Connecting to Habdec ", self.habdec_server, "... ")
self.connect()
print("Connected to Habdec ", self.habdec_server, "... ")
return
except KeyboardInterrupt:
print("Connection interruped KeyboardInterrupt")
return
except:
# print("Failed connection.")
# print('traceback: ', traceback.format_exc())
time.sleep(1)
def Start(self):
self.__habdec_run = True
self.__habdec_thread = threading.Thread(target=self.run_forever)
self.__habdec_thread.start()
self.__sentence_run = True
self.__sentence_thread = threading.Thread(target=self.__get_sentence_thread_f)
self.__sentence_thread.start()
def Stop(self):
print("Habdec Client Stopping... " + self.habdec_server)
self.__sentence_run = False
self.__habdec_run = False
if self.__sentence_thread and self.__sentence_thread.is_alive():
self.__sentence_thread.join()
try:
self.close()
self.__habdec_connection_initialized = False
except:
print("Error HabdecClient::Stop -> close()")
print(traceback.format_exc())
self.__habdec_thread = None
def __get_sentence_thread_f(self):
if not self.__habdec_connection_initialized:
self.__connect()
self.__habdec_connection_initialized = True
while self.__sentence_run:
if self.terminated:
self.__connect()
try:
self.send("cmd::sentence")
except:
print("Problem communicating Habdec")
print("traceback: ", traceback.format_exc())
time.sleep(1)
def received_message(self, m):
self.__last_connection_time = datetime.datetime.utcnow()
i_data = None
try:
i_data = m.data.decode()
except:
print(self.habdec_server + " - Can't decode data.")
if not i_data:
return
if i_data.startswith("cmd::info:sentence"):
sent_str = i_data[len("cmd::info:sentence:") :]
sentences = formatSentence.formatSentence(sent_str)
if sentences:
sent = sentences[-1]
sent_id = formatSentence.sentenceToId(sent)
if sent_id:
with self.__sentence_mtx:
self.__sentences_arr.append( sent )
self.__last_sentence_time = datetime.datetime.utcnow()
# if sent_id not in self.__sentences_dict:
# self.__sentences_dict[sent_id] = sent
# bisect.insort(self.__sentences_sorted_ids, sent_id)
# self.__last_sentence_time = datetime.datetime.utcnow()
def GetLastSentence(self):
res = None
with self.__sentence_mtx:
if len(self.__sentences_arr):
return self.__sentences_arr[-1]
# if len(self.__sentences_sorted_ids):
# res = self.__sentences_dict[self.__sentences_sorted_ids[-1]]
return res
def GetLastSentenceReceiveTime(self):
with self.__sentence_mtx:
return self.__last_sentence_time
def GetLastConnectionTime(self):
return self.__last_connection_time

Wyświetl plik

@ -0,0 +1,616 @@
#!/usr/bin/env python3
# access over HTTP
#
'''
("/habboy/api/v1/params", method=['OPTIONS', 'GET'])
("/habboy/api/v1/params/payload_id", method=['OPTIONS', 'GET', 'PUT'])
("/habboy/api/v1/payloads", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/sensors", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/sensors/<sensor>", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/sensors/<sensor>/last", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/gps", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/gps/last", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/sentences/last", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/sentences/lastdata", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/sentences/lastId", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/receiver_stats", method=['OPTIONS', 'GET'])
("/habboy/api/v1/payloads/<payload>/predict", method=['OPTIONS', 'GET'])
("/habboy/api/v1/habdec/add/<habdec_addr>", method=['OPTIONS', 'GET'])
("/habboy/api/v1/habdec/del/<habdec_addr>", method=['OPTIONS', 'GET'])
("/habboy/api/v1/habdec/get", method=['OPTIONS', 'GET'])
("/habboy/api/v1/sentence/<uploader>/<sentence>", method=['OPTIONS', 'PUT'])
("/habboy/api/v1/chasecar/<chasecar_name>", method=['OPTIONS', 'POST'])
("/habboy/api/v1/ctrl/habdec_stop", method=['OPTIONS', 'GET'])
("/habboy/api/v1/ctrl/habdec_start", method=['OPTIONS', 'GET'])
("/habboy/api/v1/ctrl/spy_stop", method=['OPTIONS', 'GET'])
("/habboy/api/v1/ctrl/spy_start", method=['OPTIONS', 'GET'])
("/habboy/api/v1/ctrl/reboot", method=['OPTIONS', 'GET'])
("/habboy/api/v1/ctrl/restart", method=['OPTIONS', 'GET'])
("/habboy/api/v1/ctrl/halt", method=['OPTIONS', 'GET'])
("/habboy/api/v1/gps", method=['OPTIONS', 'GET'])
("/habboy/api/v1/utcnow", method=['OPTIONS', 'GET'])
("/habboy/api/v1/info", method=['OPTIONS', 'GET'])
("/habboy", method=['OPTIONS', 'GET'])
('/')
'''
__all__ = ['RUN']
import os
import json
import bottle
import time
import datetime
import traceback
import sys
import shlex
import subprocess
import formatSentence
from pprint import pprint
from copy import deepcopy
from cheroot import wsgi
from cheroot.ssl.builtin import BuiltinSSLAdapter
import HabdecClient
import HabHubClient
import HabHubInterface
from get_ip import get_ip_local
DB = None
# G_EXP_BURST_ALT = 30000 # expected burst altitude - meters
G_PREDICTOR = None
G_HABDEC_CLIENTS = {}
G_HABHUB_CLIENTS = {}
G_OPTIONS = {}
G_HABDEC_CLIENTS = None
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
class JSONEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime.datetime):
return o.isoformat() + '+00:00'
else:
return json.JSONEncoder.default(self, o)
def merge_dicts(*args):
result = {}
for dictionary in args:
result.update(dictionary)
return result
def redirect_http_to_https(callback):
'''Bottle plugin that redirects all http requests to https'''
def wrapper(*args, **kwargs):
scheme = bottle.request.urlparts[0]
if scheme == 'http':
# request is http; redirect to https
bottle.redirect(bottle.request.url.replace('http', 'https', 1))
else:
# request is already https; okay to proceed
return callback(*args, **kwargs)
return wrapper
def time_to_string(i_datetime):
return i_datetime.isoformat() + '+00:00'
# return datetime.datetime.strftime(i_datetime, "%Y-%m-%d %H:%M:%S")
class EnableCors(object):
name = "enable_cors"
api = 2
def apply(self, fn, context):
def _enable_cors(*args, **kwargs):
# set CORS headers
bottle.response.headers["Access-Control-Allow-Origin"] = "*"
bottle.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
bottle.response.headers["Access-Control-Allow-Headers"] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token"
# actual request; reply with the actual response
if bottle.request.method != "OPTIONS":
return fn(*args, **kwargs)
return _enable_cors
# Create our own sub-class of Bottle's ServerAdapter
# so that we can specify SSL. Using just server='cherrypy'
# uses the default cherrypy server, which doesn't use SSL
class SSLCherryPyServer(bottle.ServerAdapter):
def run(self, handler):
server = wsgi.Server( (self.host, self.port), handler)
server.ssl_adapter = BuiltinSSLAdapter("cacert.pem", "privkey.pem")
# By default, the server will allow negotiations with extremely old protocols
# that are susceptible to attacks, so we only allow TLSv1.2
# server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1
# server.ssl_adapter.context.options |= ssl.OP_NO_TLSv1_1
try:
server.start()
finally:
server.stop()
application = bottle.app()
application.install(EnableCors())
######################################################################
######################################################################
def GetRequestValueWithDefault(i_req, i_token, i_type, defaultValue):
"""
get value from GET request
ensure proper type
return defaultValue on error or missing
"""
if type(defaultValue) != i_type:
raise ValueError("defaultValue is of wrong type")
if i_token not in i_req:
return defaultValue
val_str = i_req[i_token]
if i_type == bool:
res = defaultValue
if val_str == "1" or val_str.lower() == "true":
res = True
elif val_str == "0" or val_str.lower() == "false":
res = False
return res
elif i_type == int:
try:
res = int(val_str)
return res
except:
return defaultValue
else:
# string
return val_str
return defaultValue
@application.route("/habboy/api/v1/params", method=['OPTIONS', 'GET'])
def GetPayloadIdAndCallsign():
bottle.response.content_type = "application/javascript"
global G_OPTIONS
res = {}
res['payload_id'] = G_OPTIONS['payload_id']
res['callsign'] = G_OPTIONS['callsign']
res['payloads'] = G_OPTIONS['payloads']
res['burst'] = G_OPTIONS['burst']
with G_OPTIONS['clients_mutex']:
res['habdec_clients'] = list( G_OPTIONS['habdec_clients'].keys() )
return JSONEncoder().encode(res)
@application.route("/habboy/api/v1/params/payload_id", method=['OPTIONS', 'GET', 'PUT'])
def PayloadId():
global G_PAYLOAD_ID
global G_CALLSIGN
if bottle.request.method == 'GET':
bottle.response.content_type = "application/json"
return json.dumps( {'payload_id': G_OPTIONS['payload_id'], 'callsign': G_OPTIONS['callsign']} )
if bottle.request.method == 'PUT':
data = bottle.request.json
if 'callsign' in data and 'payload_id' in data:
old_pid = G_OPTIONS['payload_id']
new_pid = data['payload_id']
if old_pid in G_OPTIONS['habhub_clients']:
G_OPTIONS['habhub_clients'][old_pid].Stop()
del G_OPTIONS['habhub_clients'][old_pid]
G_OPTIONS['callsign'] = data['callsign']
G_OPTIONS['payload_id'] = new_pid
G_OPTIONS['habhub_clients'][new_pid] = HabHubClient.HabHubClient(new_pid)
G_OPTIONS['habhub_clients'][new_pid].Start()
@application.route("/habboy/api/v1/payloads", method=['OPTIONS', 'GET'])
def GetVehicles():
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "application/json"
data = DB.getAllPayloadIds()
return json.dumps(data)
@application.route("/habboy/api/v1/payloads/<payload>/sensors", method=['OPTIONS', 'GET'])
def GetVehicleSensors(payload):
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "application/json"
sensors_info = DB.getSensorsInfo(payload)
res = [{
'name': sens['name'],
'sensor': sens['sensor'],
'sql_data_type': sens['sql_data_type'],
} for sens in sensors_info]
return JSONEncoder().encode(res)
@application.route("/habboy/api/v1/payloads/<payload>/sensors/<sensor>", method=['OPTIONS', 'GET'])
def GetSensorData(payload, sensor):
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "application/json"
last_time = GetRequestValueWithDefault(bottle.request.query, "time", str, time_to_string(datetime.datetime.utcfromtimestamp(0)))
sensors = [sensor]
if sensor == "*":
sensors = DB.getSensorsList(payload)
elif "," in sensor:
sensors = sensor.split(",")
if "time" in sensors:
sensors.remove("time")
res = {}
for _sensor in sensors:
data = DB.getTelemetryByTime(payload, _sensor, last_time)
if data:
data["times"] = [
time_to_string(x) for x in data["times"]
]
res[_sensor] = data
return json.dumps(res)
@application.route("/habboy/api/v1/payloads/<payload>/sensors/<sensor>/last", method=['OPTIONS', 'GET'])
def GetSensorDataLast(payload, sensor):
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "application/json"
sensors = [sensor]
if sensor == "*":
sensors = DB.getSensorsList(payload)
elif "," in sensor:
sensors = sensor.split(",")
if "time" in sensors:
sensors.remove("time")
res = {}
for _sensor in sensors:
data = DB.getTelemetryLast(payload, _sensor)
if data:
data["times"] = [time_to_string(x) for x in data["times"] ]
res[_sensor] = data
return json.dumps(res)
@application.route("/habboy/api/v1/payloads/<payload>/gps", method=['OPTIONS', 'GET'])
def GetGps(payload):
"""
result:
[ ["014056", [52.15429, 21.03445, 7223]], ... ]
"""
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "application/json"
last_time = GetRequestValueWithDefault(bottle.request.query, "time", str, time_to_string(datetime.datetime.utcfromtimestamp(0)))
lat = DB.getTelemetryByTime(payload, "latitude", time_to_string(datetime.datetime.utcfromtimestamp(0)))
lon = DB.getTelemetryByTime(payload, "longitude", time_to_string(datetime.datetime.utcfromtimestamp(0)))
alt = DB.getTelemetryByTime(payload, "altitude", time_to_string(datetime.datetime.utcfromtimestamp(0)))
if not lat or not lon or not alt:
return "{}"
lat["times"] = [time_to_string(x) for x in lat["times"]]
lon["times"] = [time_to_string(x) for x in lon["times"]]
alt["times"] = [time_to_string(x) for x in alt["times"]]
data = list(zip(lat["values"], lon["values"], alt["values"]))
times = lat["times"]
res = list(zip(times, data))
return json.dumps(res)
@application.route("/habboy/api/v1/payloads/<payload>/gps/last", method=['OPTIONS', 'GET'])
def GetGpsLast(payload):
"""
result:
[ ["014059", [52.15429, 21.03445, 12223]] ]
"""
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "application/json"
lat = DB.getTelemetryLast(payload, "latitude")
lon = DB.getTelemetryLast(payload, "longitude")
alt = DB.getTelemetryLast(payload, "altitude")
if not lat or not lon or not alt:
return "{}"
lat["times"] = [time_to_string(x) for x in lat["times"]]
lon["times"] = [time_to_string(x) for x in lon["times"]]
alt["times"] = [time_to_string(x) for x in alt["times"]]
data = list(zip(lat["values"], lon["values"], alt["values"]))
times = lat["times"]
res = list(zip(times, data))
return json.dumps(res)
@application.route("/habboy/api/v1/payloads/<payload>/sentences/last", method=['OPTIONS', 'GET'])
def GetSentenceLast(payload):
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "text/plain"
last_sentence_data = DB.getLastSentence(payload)
# return last_sentence_data[-3]
return last_sentence_data['_SENTENCE']
@application.route("/habboy/api/v1/payloads/<payload>/sentences/lastdata", method=['OPTIONS', 'GET'])
def GetSentenceLastData(payload):
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "application/json"
last_sentence_data = DB.getLastSentence(payload)
return JSONEncoder().encode( last_sentence_data )
@application.route("/habboy/api/v1/payloads/<payload>/sentences/lastId", method=['OPTIONS', 'GET'])
def GetSentenceLastId(payload):
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "text/plain"
last_sentence_id = DB.getLastSentenceId(payload)
return last_sentence_id
@application.route("/habboy/api/v1/payloads/<payload>/receiver_stats", method=['OPTIONS', 'GET'])
def GetReceiverStats(payload):
global G_OPTIONS
DB = G_OPTIONS['sentences_db']
bottle.response.content_type = "json"
res = DB.getReceiversStats(payload)
return res
@application.route("/habboy/api/v1/payloads/<payload>/predict", method=['OPTIONS', 'GET'])
def GetPayloadPrediction(payload):
bottle.response.content_type = "application/json"
global G_OPTIONS
get_predict_fun = G_OPTIONS['get_predict']
if get_predict_fun:
flight_path = get_predict_fun()
return JSONEncoder().encode( flight_path )
return json.dumps( {} )
@application.route("/habboy/api/v1/habdec/add/<habdec_addr>", method=['OPTIONS', 'GET'])
def HabdecAdd(habdec_addr):
bottle.response.content_type = "text/plain"
global G_OPTIONS
if not habdec_addr.lower().startswith('ws://'):
habdec_addr = 'ws://' + habdec_addr
with G_OPTIONS['clients_mutex']:
if habdec_addr in G_OPTIONS['habdec_clients']:
return 'already exists'
if not habdec_addr.lower().startswith('ws://'):
habdec_addr = 'ws://' + habdec_addr
if habdec_addr not in G_OPTIONS['habdec_clients']:
G_OPTIONS['habdec_clients'][habdec_addr] = HabdecClient.HabdecClient(habdec_addr)
G_OPTIONS['habdec_clients'][habdec_addr].Start()
return "OK"
@application.route("/habboy/api/v1/habdec/del/<habdec_addr>", method=['OPTIONS', 'GET'])
def HabdecDel(habdec_addr):
global G_OPTIONS
if not habdec_addr.lower().startswith('ws://'):
habdec_addr = 'ws://' + habdec_addr
with G_OPTIONS['clients_mutex']:
if habdec_addr in G_OPTIONS['habdec_clients']:
G_OPTIONS['habdec_clients'][habdec_addr].Stop()
del G_OPTIONS['habdec_clients'][habdec_addr]
bottle.response.content_type = "text/plain"
return "OK"
@application.route("/habboy/api/v1/habdec/get", method=['OPTIONS', 'GET'])
def HabdecGet():
global G_OPTIONS
bottle.response.content_type = "application/json"
with G_OPTIONS['clients_mutex']:
habdecs = G_OPTIONS['habdec_clients'].keys()
return json.dumps( list(habdecs) )
@application.route("/habboy/api/v1/gps", method=['OPTIONS', 'GET'])
def GetHabboyGps():
bottle.response.content_type = "application/json"
if G_OPTIONS['get_gps']:
gps = deepcopy( G_OPTIONS['get_gps']() )
gps['time'] = gps['time'].isoformat() + '+00:00'
gps['parse_timestamp'] = gps['parse_timestamp'].isoformat() + '+00:00'
return json.dumps( gps )
return json.dumps( {} )
@application.route("/habboy/api/v1/utcnow", method=['OPTIONS', 'GET'])
def GetUtcNow():
bottle.response.content_type = "text/plain"
return datetime.datetime.utcnow().isoformat() + '+00:00'
@application.route("/habboy/api/v1/info", method=['OPTIONS', 'GET'])
def GetHabboyInfo():
global G_OPTIONS
bottle.response.content_type = "application/json"
res = {}
if G_OPTIONS['get_stats']:
res = G_OPTIONS['get_stats']()
return JSONEncoder().encode( res )
@application.route("/habboy/api/v1/chasecar/<chasecar_name>", method=['OPTIONS', 'POST'])
def Habdec_ChasecarUpload(chasecar_name):
bottle.response.content_type = "application/json"
if not chasecar_name.endswith('_chase'):
return JSONEncoder().encode( {'result': 'error', 'what': 'car name does not end with _chase'} )
if bottle.request.method == 'POST':
params = merge_dicts(dict(bottle.request.forms), dict(bottle.request.query.decode()))
params = list(params.keys())[0] # this is very weird
params = json.loads(params)
try:
data = {'vehicle' : chasecar_name,
'time' : datetime.datetime.utcnow().strftime("%H%M%S"),
'lat' : params["latitude"],
'lon' : params["longitude"],
'alt' : params["altitude"],
'speed' : params["ground_speed_mps"],
'heading' : params["heading"],
'pass' : "aurora"}
except KeyError as e:
return JSONEncoder().encode( {'result': 'error', 'what': 'KeyError: ' + str(e)} )
try:
if not HabHubInterface.uploadChaseCar(data):
return JSONEncoder().encode( {'result': 'error', 'what': 'Connection Error'} )
except:
eprint(traceback.format_exc())
return JSONEncoder().encode( {'result': 'error', 'what': 'Other Exception'} )
return JSONEncoder().encode( {'result': 'ok'} )
return json.dumps( {} )
@application.route("/habboy/api/v1/ctrl/habdec_stop", method=['OPTIONS', 'GET'])
def habdec_stop():
os.system('sudo systemctl stop habdec')
bottle.response.content_type = "application/json"
return json.dumps({})
@application.route("/habboy/api/v1/ctrl/habdec_start", method=['OPTIONS', 'GET'])
def habdec_start():
os.system('sudo systemctl start habdec')
bottle.response.content_type = "application/json"
return json.dumps({})
@application.route("/habboy/api/v1/ctrl/spy_stop", method=['OPTIONS', 'GET'])
def spy_stop():
os.system('sudo systemctl stop spyserver')
bottle.response.content_type = "application/json"
return json.dumps({})
@application.route("/habboy/api/v1/ctrl/spy_start", method=['OPTIONS', 'GET'])
def spy_start():
os.system('sudo systemctl start spyserver')
bottle.response.content_type = "application/json"
return json.dumps({})
@application.route("/habboy/api/v1/ctrl/reboot", method=['OPTIONS', 'GET'])
def Reboot():
os.system('sudo reboot')
@application.route("/habboy/api/v1/sentence/<uploader>/<sentence>", method=['OPTIONS', 'PUT'])
def SententenceUpload(uploader, sentence):
if bottle.request.method == 'PUT':
# data = bottle.request.json
if sentence:
if G_OPTIONS['sentences_db'].insert(i_sentence = sentence, i_RECEIVER = uploader):
return json.dumps ( {'result': 1} )
else:
eprint('DB Input FAIL')
return json.dumps ( {'result': 0} )
@application.route("/habboy/api/v1/ctrl/restart", method=['OPTIONS', 'GET'])
def Restart():
os.system('sudo systemctl daemon-reload')
os.system('sudo systemctl restart habboy_advertise.service')
os.system('sudo systemctl restart habdec_advertise.service')
os.system('sudo systemctl restart habdec.service')
os.system('sudo systemctl restart habboy.service')
bottle.response.content_type = "application/json"
return json.dumps({})
@application.route("/habboy/api/v1/ctrl/halt", method=['OPTIONS', 'GET'])
def Halt():
os.system('sudo shutdown now')
bottle.response.content_type = "application/json"
return json.dumps({})
@application.route("/habboy", method=['OPTIONS', 'GET'])
def HabboyDiscovery():
bottle.response.content_type = "application/json"
return json.dumps({'HABBOY': 1})
@application.route('/')
def route_root():
new_url = bottle.request.url[0:bottle.request.url.rindex(':')] + '/habboy'
res = '<meta http-equiv="refresh" content="0; url={}" />'.format(new_url)
return res
def RUN(hostname,
port,
is_https,
i_opts,
debug=True,
reloader=True):
global DB
DB = i_opts['sentences_db']
global G_OPTIONS
G_OPTIONS = i_opts
G_OPTIONS['start_time'] = datetime.datetime.utcnow()
if not hostname:
hostname = get_ip_local()
if is_https:
print("AS HTTPS")
application.install(redirect_http_to_https)
bottle.run(
host=hostname,
port=port,
debug=debug,
reloader=reloader,
server=SSLCherryPyServer,
)
else:
bottle.run(host=hostname, port=port, debug=debug, reloader=reloader, quiet=True)
if __name__ == "__main__":
pprint( get_process_stats(['habdecWebsocketServer', 'habboy_data']) )

Wyświetl plik

@ -0,0 +1,801 @@
#!/usr/bin/env python3
import os
import string
import threading
from pprint import pprint, pformat
# import bisect
import datetime
import dateutil.parser
import traceback
import json
import math
from copy import deepcopy
import formatSentence
import HabHubInterface
import sqlite3
from sqlite3 import Error as sqerr
C_BLACK = "\033[1;30m"
C_RED = "\033[1;31m"
C_GREEN = "\033[1;32m"
C_BROWN = "\033[1;33m"
C_BLUE = "\033[1;34m"
C_MAGENTA = "\033[1;35m"
C_CYAN = "\033[1;36m"
C_LIGHTGREY = "\033[1;37m"
C_OFF = "\033[0m"
C_CLEAR = "\033[2K"
def sentence_time_formatter(i_str):
result = datetime.datetime.utcnow()
in_time = None
if ":" in i_str:
in_time = datetime.datetime.strptime(i_str, "%H:%M:%S")
else:
if len(i_str) < 6:
i_str = i_str.zfill(6)
in_time = datetime.datetime.strptime(i_str, "%H%M%S")
result = result.replace(hour = in_time.hour)
result = result.replace(minute = in_time.minute)
result = result.replace(second = in_time.second)
result = result.replace(microsecond = 0)
return result
def coordinate_formatter(i_coord, i_format):
if i_format == 'dd.dddd': # decimals
degrees = float(i_coord)
return degrees
elif i_format == 'ddmm.mmmm': # degrees/minutes 02145.4512 = 21 degrees, 45 minutes 45.12 seconds
coord = float(i_coord)
degrees = math.trunc(coord/100.0)
minutes = coord - 100.0 * degrees
return (degrees + minutes/60.0)
def sensor_type_converter( i_sensor ):
s_name = i_sensor['name']
s_type = i_sensor['sensor']
if s_type == "base.ascii_int":
return lambda x: int(float(x))
elif s_type == "base.ascii_float":
return lambda x: float(x)
elif s_type == "base.string":
if s_name == 'time':
return sentence_time_formatter
return lambda x: x
elif s_type == "stdtelem.time":
return sentence_time_formatter
elif s_type == "stdtelem.coordinate":
if 'format' in i_sensor:
return lambda x: coordinate_formatter(x, i_sensor['format'])
else:
return lambda x: float(x)
else:
lambda x: x
def is_sensor_numeric(i_sensor_type):
if i_sensor_type == "base.ascii_int":
return True
elif i_sensor_type == "base.ascii_float":
return True
elif i_sensor_type == "base.string":
return False
elif i_sensor_type == "stdtelem.time":
return False
elif i_sensor_type == "stdtelem.coordinate":
return False
else:
return False
def sensor_sql_type(i_sensor):
s_type = i_sensor["sensor"]
if s_type == "base.ascii_int":
return "integer"
elif s_type == "base.ascii_float":
return "real"
elif s_type == "base.string":
if(i_sensor['name'] == 'time'):
return 'timestamp'
return "text"
elif s_type == "stdtelem.time":
return "timestamp"
elif s_type == "stdtelem.coordinate":
return "real"
else:
return "text"
class VehicleData(object):
"""
keeps parsed data for specific callsign
"""
def __init__(self, i_sentence_info):
# print("VehicleData init")
# pprint(i_sentence_info)
if not i_sentence_info:
print('VehicleData init, no sentence info')
raise ValueError
self.__IDs = [] # list of sentence TIMESTAMPS
# indexed with telemetry sensor name
# each item is a dict
# self.__data['altitude']['values'] = [] # raw values
# self.__data['altitude']['accum'] = [] # sum of values
# self.__data['altitude']['min'] = []
# self.__data['altitude']['max'] = []
# self.__data['altitude']['avg'] = []
self.__data = {}
# info about telemetry datatypes
# indexed by position in sentence, excluding callsing
self.__data_info = deepcopy(i_sentence_info)
# self.__data_info = HabHubInterface.getSentenceInfo(
# self.__payloadName, i_sentence
# )
if not self.__data_info:
print(10 * "VehicleData init - no sentence info. exit.\n")
return
raise ValueError
for i in range(len(self.__data_info)):
for k in self.__data_info[i]:
self.__data_info[i][str(k)] = str(self.__data_info[i][k])
for i in range(len(self.__data_info)):
if "sensor" not in self.__data_info[i]:
continue
self.__data_info[i]["converter"] = sensor_type_converter( self.__data_info[i] )
self.__data_info[i]["is_numeric"] = is_sensor_numeric( self.__data_info[i]["sensor"] )
def __repr__(self):
print("Vehicle Data:")
print("__data")
pprint(self.__data)
pprint(self.__data_info)
def to_str(self):
return pformat(self.__data)
def add(self, i_sentence, i_sentence_timestamp):
sentences = formatSentence.formatSentence(i_sentence)
for s in sentences:
sensor_values_str_arr = formatSentence.getData(s)
if len(sensor_values_str_arr) != len(self.__data_info):
pprint(self.__data_info)
raise ValueError(
"VehicleData ",
# self.__payloadName,
" Wrong Sentence Format (values count): ",
i_sentence,
len(sensor_values_str_arr),
len(self.__data_info),
)
sentence_id = i_sentence_timestamp
# do not accept sentences older than last - this would require to recompute all stats
if self.__IDs and sentence_id <= self.__IDs[-1]:
return
self.__IDs.append(sentence_id)
# insert_index = self.__IDs.index(sentence_id)
# sentence_time = sentence_time_formatter(sensor_values_str_arr[1])
# self.__times.append(i_sentence_timestamp)
if not self.__data:
for i in range( 2, len(sensor_values_str_arr) ): # skip sentence_id and time
sensor = self.__data_info[i]["name"]
self.__data[sensor] = {}
self.__data[sensor]["is_numeric"] = self.__data_info[i]["is_numeric"]
self.__data[sensor]["values"] = [] # raw values
if self.__data_info[i]["is_numeric"]:
self.__data[sensor]["accum"] = [] # sum of values
self.__data[sensor]["min"] = []
self.__data[sensor]["max"] = []
self.__data[sensor]["avg"] = []
self.__data[sensor]["dVdT"] = []
for i in range(2, len(sensor_values_str_arr)): # skip sentence_id and time
sensor = self.__data_info[i]["name"]
# value
converter = self.__data_info[i]["converter"]
value = converter(sensor_values_str_arr[i])
self.__data[sensor]["values"].append(value)
if not self.__data_info[i]["is_numeric"]:
continue
# update min/max/avg
#
self.__data[sensor]["accum"].append(value)
self.__data[sensor]["min"].append(value)
self.__data[sensor]["max"].append(value)
self.__data[sensor]["avg"].append(value)
self.__data[sensor]["dVdT"].append(value) # not a good initial value - fix later
if len(self.__data[sensor]["values"]) > 1:
self.__data[sensor]["min"][-1] = min(
self.__data[sensor]["min"][-2],
value
)
self.__data[sensor]["max"][-1] = max(
self.__data[sensor]["max"][-2],
value
)
self.__data[sensor]["accum"][-1] = self.__data[sensor]["accum"][-2] + value
self.__data[sensor]["avg"][-1] = float(self.__data[sensor]["accum"][-1]) / len(self.__data[sensor]["accum"])
# compute change over time - with dT at least 5 seconds
#
prev_index = len(self.__IDs) - 2
prev_time = self.__IDs[prev_index]
prev_value = self.__data[sensor]["values"][prev_index]
dT = float( (i_sentence_timestamp - prev_time).total_seconds() ) or 1
dVdT = float(value-prev_value) / dT
while prev_index >= 0:
prev_time = self.__IDs[prev_index]
dT = float( (i_sentence_timestamp - prev_time).total_seconds() )
if dT < 5:
prev_index -= 1
continue
else:
prev_value = self.__data[sensor]["values"][prev_index]
dVdT = float(value-prev_value) / dT
break
self.__data[sensor]["dVdT"][-1] = dVdT
# fix first dVdT value
if len(self.__data[sensor]["dVdT"]) == 2:
self.__data[sensor]["dVdT"][0] = self.__data[sensor]["dVdT"][1]
def get_last(self, i_sensor_name):
result = {}
try:
result["is_numeric"] = self.__data[i_sensor_name]["is_numeric"]
result["values"] = [self.__data[i_sensor_name]["values"][-1]]
result["times"] = [self.__IDs[-1]]
if self.__data[i_sensor_name]["is_numeric"]:
result["min"] = [self.__data[i_sensor_name]["min"][-1]]
result["max"] = [self.__data[i_sensor_name]["max"][-1]]
result["avg"] = [self.__data[i_sensor_name]["avg"][-1]]
result["dVdT"] = [self.__data[i_sensor_name]["dVdT"][-1]]
except KeyError:
return result
return result
def get_by_time(self, i_sensor_name, i_time):
"""
return sensor data past i_time (excluded)
"""
if i_sensor_name not in self.__data:
return {}
left_i = 0
for i in range(len(self.__IDs)):
left_i = i
# print(self.__IDs[left_i], i_time, self.__IDs[left_i] > i_time)
if self.__IDs[left_i] > i_time:
break
result = {}
result["is_numeric"] = self.__data[i_sensor_name]["is_numeric"]
result["values"] = self.__data[i_sensor_name]["values"][left_i:]
result["times"] = self.__IDs[left_i:]
if self.__data[i_sensor_name]["is_numeric"]:
result["min"] = self.__data[i_sensor_name]["min"][left_i:]
result["max"] = self.__data[i_sensor_name]["max"][left_i:]
result["avg"] = self.__data[i_sensor_name]["avg"][left_i:]
result["dVdT"] = self.__data[i_sensor_name]["dVdT"][left_i:]
# print(i_sensor_name, len(result['times']),len(result['values']), len(result['dt']) )
return result
def sensorsList(self):
# if self.__data: return list(self.__data.keys())
if self.__data_info:
return [ s['name'] for s in self.__data_info ]
return [None]
def sensorsInfo(self):
if self.__data_info:
return copy.deepcopy( self.__data_info )
# return [ s['name'] for s in self.__data_info ]
return [None]
def verify(self):
if self.__IDs != sorted(self.__IDs):
print ("IDs - unsorted")
if self.__IDs != sorted(self.__IDs):
print ('times unsorted')
pprint(self.__IDs)
class SentencesDB(object):
def __init__(self, db_file):
if not db_file or db_file == "":
raise ValueError("SentencesDB: no file specified.")
self.__mutex = threading.Lock()
self.__sensorsInfo = (
{}
) # functions to convert from string to real data, indexed with payloadId
self.__sqldb = None
self.__sqldb_file = db_file
self.__callsignToPayloadId = {}
self.__sensorToPosition = {} # convert payload_id/sensor_name to position in sentence INCLUDING callsign
self.__vehicles_data = {} # class VehicleData, indexed by payloadId
self.__initSQLDB()
def __initSQLDB(self):
if self.__sqldb:
return
self.__sqldb = sqlite3.connect(self.__sqldb_file, check_same_thread=False, detect_types=sqlite3.PARSE_DECLTYPES | sqlite3.PARSE_COLNAMES)
self.__sqldb.row_factory = sqlite3.Row
self.__createPayloadInfoTable()
self.__loadSensorsInfo()
for payload_id in self.__sensorsInfo:
self.__createPayloadTable(payload_id)
self.__initVehiclesData()
def __createPayloadInfoTable(self):
"""
one global metadata table
keeps info for each table
"""
meta_table_creation_ = "CREATE TABLE IF NOT EXISTS PayloadInfo ("
meta_table_creation_ += " PayloadId TEXT PRIMARY KEY,"
meta_table_creation_ += " callsign TEXT NOT NULL,"
meta_table_creation_ += " SentenceInfo TEXT NOT NULL"
meta_table_creation_ += ");"
try:
with self.__mutex:
cur = self.__sqldb.cursor()
cur.execute(meta_table_creation_)
self.__sqldb.commit()
except sqerr as e:
print(e)
import traceback
print(traceback.format_exc())
except:
import traceback
print(traceback.format_exc())
def __createPayloadTable(self, i_payloadId):
"""
per payload table
"""
payload_table_creation_ = "CREATE TABLE IF NOT EXISTS {} (".format(
"P_" + i_payloadId
)
for sensor_info in self.__sensorsInfo[i_payloadId]:
payload_table_creation_ += (
"\n\t" + sensor_info["name"] + " " + sensor_info["sql_data_type"] + ","
)
payload_table_creation_ += "\n\t_SENTENCE text,\n\t_RECEIVER text,\n\t_INSERT_TIME timestamp,"
payload_table_creation_ += "\n\tPRIMARY KEY(sentence_id, time, _RECEIVER)\n);"
cur = self.__sqldb.cursor()
try:
cur.execute(payload_table_creation_)
self.__sqldb.commit()
except sqerr as e:
print(
"error cur.execute(payload_table_creation_) - payload_id = ",
i_payloadId,
)
print(e)
print(payload_table_creation_)
import traceback
print(traceback.format_exc())
except:
import traceback
print(traceback.format_exc())
def __loadSensorsInfo(self):
if self.__sensorsInfo and len(self.__sensorsInfo.keys()):
print("__loadSensorsInfo - early exit")
return
# load from disk
#
habitat_data = {}
try:
with self.__mutex:
cur = self.__sqldb.cursor()
cur.execute("SELECT PayloadId,callsign,SentenceInfo FROM PayloadInfo;")
for PayloadId, callsign, sensors_info_str in cur.fetchall():
habitat_data[PayloadId] = json.loads(sensors_info_str)
self.__callsignToPayloadId[callsign] = PayloadId
except sqerr as e:
print(e)
import traceback
print(traceback.format_exc())
# convert from habitat data
#
for PayloadId in habitat_data:
self.__sensorsInfo[PayloadId] = []
self.__sensorToPosition[PayloadId] = {'callsign': 0}
sensorPostiion = 1 # start with 1 because callsign is counted in indexing
for sensor_info in habitat_data[PayloadId]:
sensor_info["sql_data_type"] = sensor_sql_type( sensor_info )
sensor_info["converter"] = sensor_type_converter( sensor_info )
# sensor_info["sql_primary_key"] = sensor_info["name"] == "sentence_id"
self.__sensorsInfo[PayloadId].append(sensor_info)
self.__sensorToPosition[PayloadId][sensor_info['name']] = sensorPostiion
sensorPostiion += 1
def __initVehiclesData(self):
# return
if not self.__sqldb:
return
allPayloadIds = self.getAllPayloadIds()
print("allPayloadIds:")
pprint(allPayloadIds)
sentences_count = {}
cur = self.__sqldb.cursor()
for pid,callsign in allPayloadIds:
sentences_count[pid] = 0
# update vehicles data
if pid not in self.__vehicles_data:
_t = VehicleData(self.getSensorsInfo(pid))
self.__vehicles_data[pid] = _t
try:
cur.execute(" select time,_SENTENCE from {};".format("P_" + pid))
except sqlite3.OperationalError as e:
if 'no such table: P_' in str(e):
continue # no data/table for this payload_id
else:
print(traceback.format_exc())
continue
for time, sentence in cur.fetchall():
try:
self.__vehicles_data[pid].add(sentence, time)
sentences_count[pid] += 1
except:
print("Can't parse ", sentence)
print(traceback.format_exc())
# if pid in self.__vehicles_data: print( self.__vehicles_data[pid].to_str() )
if sentences_count:
print("Restored Vehicles Data from DB:")
for k, v in sentences_count.items():
callsign = self.payloadIdToCallsign(k)
print("\t", callsign, v)
# for pid in self.__vehicles_data:
# print(pid)
# print(self.__vehicles_data[pid])
# for pid in self.__vehicles_data:
# self.__vehicles_data[pid].verify()
def callsignToPayloadId(self, i_callsign):
if i_callsign in self.__callsignToPayloadId:
return self.__callsignToPayloadId[i_callsign]
return None
def create_empty(self):
self.__initSQLDB()
def payloadIdToCallsign(self, i_payloadId):
try:
with self.__mutex:
cur = self.__sqldb.cursor()
cur.execute(
'SELECT callsign FROM PayloadInfo WHERE PayloadId is "{}";'.format(
str(i_payloadId)
)
)
return cur.fetchall()[0][0]
except sqerr as e:
print(e)
import traceback
print(traceback.format_exc())
return None
except IndexError:
return None
def updatePayloadInfo(self, i_payloadId, i_sentence=None):
callsign = HabHubInterface.getCallsignsForPayloadId(i_payloadId)
sentence_info = HabHubInterface.getSentenceInfo(i_payloadId, i_sentence)
if not sentence_info:
print("UpdatePayloadInfo - No Sentence Info for payload ", i_payloadId)
return
# HACK !
# time field can have many names, lets always use 'time'
for i in range(len(sentence_info)):
if 'time' in sentence_info[i]['name']:
sentence_info[i]['name'] = 'time'
break
sql_insert = (
"REPLACE INTO PayloadInfo(PayloadId, callsign, SentenceInfo) VALUES(?,?,?)"
)
try:
with self.__mutex:
cur = self.__sqldb.cursor()
cur.execute(
sql_insert,
(
i_payloadId,
callsign,
json.dumps(sentence_info, sort_keys=True, indent=4),
),
)
self.__sqldb.commit()
except sqerr as e:
print(e)
import traceback
print(traceback.format_exc())
def getAllPayloadIds(self):
try:
with self.__mutex:
cur = self.__sqldb.cursor()
cur.execute("select PayloadId, callsign from PayloadInfo;")
res = [ [x[0], x[1]] for x in cur.fetchall()]
return res
except sqerr as e:
print(e)
import traceback
print(traceback.format_exc())
def getInfo(self):
try:
with self.__mutex:
cur = self.__sqldb.cursor()
cur.execute("select * from PayloadInfo;")
res = [list(x) for x in cur.fetchall()]
res = [ [x[0], x[1], json.loads(x[2])] for x in res]
return res
except sqerr as e:
print(e)
import traceback
print(traceback.format_exc())
def insert(self, i_sentence, i_RECEIVER="unknown"):
if not i_sentence:
return
sentences = formatSentence.formatSentence(i_sentence)
if not sentences:
return
with self.__mutex:
for sentence in sentences:
callsign = formatSentence.sentenceToCallsign(sentence)
payload_id = self.callsignToPayloadId(callsign)
if not payload_id:
print("DB Insert -- Unknown callsign: ", callsign)
continue
sent_id = formatSentence.sentenceToId(sentence)
if not self.__sensorsInfo:
print("DB Insert -- No sentence data info. returning.")
return
# get data from sentence and convert from string to real types
sensors_data = formatSentence.getData(sentence)
try:
for i in range(len(sensors_data)):
converter = self.__sensorsInfo[payload_id][i]["converter"]
sensors_data[i] = converter(sensors_data[i])
except:
print("DB Insert -- Error converting sentence fields to data.")
print(traceback.format_exc())
continue
# _SENTENCE field
sensors_data.append(sentence)
# _RECEIVER field
sensors_data.append(str(i_RECEIVER))
# _INSERT_TIME field
sensors_data.append(datetime.datetime.utcnow())
sql_insert = "INSERT INTO {}(".format("P_" + payload_id)
sql_insert += ",".join(
[sensor["name"] for sensor in self.__sensorsInfo[payload_id]]
)
sql_insert += ", _SENTENCE, _RECEIVER, _INSERT_TIME"
sql_insert += ")"
sql_insert += (
"\n\tVALUES(" + ",".join(["?"] * len(sensors_data)) + ")"
)
cur = self.__sqldb.cursor()
try:
cur.execute(sql_insert, sensors_data)
self.__sqldb.commit()
# print( cur.lastrowid )
except sqlite3.IntegrityError:
pass
# print("sqlite3.IntegrityError - already inserted ?")
except sqerr as e:
print(e)
# update vehicles data
if payload_id not in self.__vehicles_data:
self.__vehicles_data[payload_id] = VehicleData(
self.getSensorsInfo(payload_id)
)
try:
sentence_timestamp = sensors_data[ self.__sensorToPosition[payload_id]['time'] -1 ]
self.__vehicles_data[payload_id].add(sentence, sentence_timestamp)
except:
print("DB Insert -- Can't parse ", sentence)
print(traceback.format_exc())
return True
def getSensorsList(self, i_payloadId):
with self.__mutex:
if i_payloadId in self.__vehicles_data:
return deepcopy( self.__vehicles_data[i_payloadId].sensorsList() )
else:
pass
# print(self.__vehicles_data.keys())
return []
def getSensorsInfo(self, i_payloadId):
with self.__mutex:
if i_payloadId in self.__sensorsInfo:
return deepcopy( self.__sensorsInfo[i_payloadId] )
return None
def getTelemetryLast(self, i_payloadId, i_sensor_name):
with self.__mutex:
if not list(self.__vehicles_data.keys()):
return {}
if i_payloadId not in self.__vehicles_data:
return {}
return self.__vehicles_data[i_payloadId].get_last(i_sensor_name)
def getTelemetryByTime(self, i_payloadId, i_sensor_name, i_time):
_t = i_time
if type(_t) == type(""):
# _t = datetime.datetime.strptime(_t, "%Y-%m-%d %H:%M:%S")
_t = dateutil.parser.parse(_t, ignoretz=1)
with self.__mutex:
if not list(self.__vehicles_data.keys()):
return []
if i_payloadId not in self.__vehicles_data:
return []
return self.__vehicles_data[i_payloadId].get_by_time(i_sensor_name, _t)
def getLastSentence(self, i_payloadId):
if not i_payloadId:
print("getLastSentence: i_payloadId = ", i_payloadId)
return
if not self.__sqldb:
return None
with self.__mutex:
tab_name = "P_" + i_payloadId
cur = self.__sqldb.cursor()
# cur.execute("select MAX(time) from {};".format(tab_name))
cur.execute("select MAX(_INSERT_TIME) from {};".format(tab_name))
last_time = cur.fetchone()[0]
if last_time:
cur.execute(
# "select * from {} where time is '{}';".format(
"select * from {} where _INSERT_TIME is '{}';".format(
tab_name, last_time
)
)
values = cur.fetchall()
return dict(values[0])
def getLastSentenceId(self, i_payloadId):
if not i_payloadId:
print("getLastSentenceId: i_payloadId = ", i_payloadId)
return
if not self.__sqldb:
return
with self.__mutex:
tab_name = "P_" + i_payloadId
cur = self.__sqldb.cursor()
cur.execute("select MAX(sentence_id) from {};".format(tab_name))
last_sentence_id = cur.fetchone()[0]
if last_sentence_id:
return last_sentence_id
return
def getReceiversStats(self, i_payloadId):
if not i_payloadId:
return
if not self.__sqldb:
return
with self.__mutex:
try:
c = self.__sqldb.cursor()
tab_name = "P_" + i_payloadId
c.execute("SELECT DISTINCT _RECEIVER FROM {}".format(tab_name))
all_receivers = c.fetchall()
all_receivers = [a[0] for a in all_receivers]
# print(all_receivers)
receiver_stats = {}
for r in all_receivers:
c.execute(
'SELECT COUNT(sentence_id) FROM "{}" WHERE _RECEIVER = "{}"'.format(
tab_name, r
)
)
receiver_stats[r] = int(c.fetchone()[0])
# pprint(receiver_stats)
return receiver_stats
except sqlite3.OperationalError as e:
if 'no such table: P_' in str(e):
return None # no data/table for this payload_id
else:
print(traceback.format_exc())
return None
return
if __name__ == "__main__":
print(sentence_time_formatter('123456'))
print(sentence_time_formatter('12:34:56'))

Wyświetl plik

@ -0,0 +1,36 @@
[
{
"name": "sentence_id",
"sensor": "base.ascii_int"
},
{
"name": "time",
"sensor": "stdtelem.time"
},
{
"format": "dd.dddd",
"name": "latitude",
"sensor": "stdtelem.coordinate"
},
{
"format": "dd.dddd",
"name": "longitude",
"sensor": "stdtelem.coordinate"
},
{
"name": "altitude",
"sensor": "base.ascii_int"
},
{
"name": "satellites",
"sensor": "base.ascii_int"
},
{
"name": "fix_age",
"sensor": "base.ascii_int"
},
{
"name": "temp",
"sensor": "base.ascii_int"
}
]

Wyświetl plik

@ -0,0 +1,110 @@
#!/usr/bin/env python3
import string
"""
Sanitize sentence string.
Calc and verify CRC code.
"""
def _hex(Character):
_hexTable = "0123456789ABCDEF"
return _hexTable[Character]
def crc(i_str):
CRC = 0xFFFF
# xPolynomial = 0x1021;
for i in range(len(i_str)):
CRC ^= ord(i_str[i]) << 8
for j in range(8):
if CRC & 0x8000:
CRC = (CRC << 1) ^ 0x1021
else:
CRC <<= 1
result = ""
result += _hex((CRC >> 12) & 15)
result += _hex((CRC >> 8) & 15)
result += _hex((CRC >> 4) & 15)
result += _hex(CRC & 15)
return result
def verifyCrc(i_sent):
i_crc = i_sent[i_sent.rfind("*") + 1 :]
sent = i_sent[: i_sent.rfind("*")]
return i_crc == crc(sent)
def formatSentence(i_sent):
if not i_sent:
return []
lines = i_sent.split("\n")
result = []
for l in lines:
dollar_index = l.rfind("$")
l = l[dollar_index + 1 :]
star_index = l.find("*")
if star_index == -1:
continue
l = l[: star_index + 5]
sentence = l[:-5]
crc = l[-4:]
result.append(sentence + "*" + crc)
return result
def sentenceToCallsign(i_sent):
sentences = formatSentence(i_sent)
if not sentences:
return None
sentence = sentences[-1]
tokens = sentence.split(",")
if tokens:
return str(tokens[0])
return None
def sentenceToId(i_sent):
sentences = formatSentence(i_sent)
if not sentences:
return None
sentence = sentences[-1]
tokens = sentence.split(",")
if len(tokens) > 1:
return int(tokens[1])
return None
def getData(i_sent):
sentences = formatSentence(i_sent)
if not sentences:
return None
sentence = sentences[-1]
tokens = sentence.split(",")
if not tokens:
return None
# remove callsign
tokens = tokens[1:]
# remove CRC
tokens[-1] = tokens[-1][0 : tokens[-1].find("*")]
return tokens
if __name__ == "__main__":
s = formatSentence(
"$$$fro3,2141,224553,52.09318,21.00429,127,0,0,0,0,D*5094 DESCEND"
)[-1]
print(s)
print((sentenceToId(s)))
print((getData(s)))

Wyświetl plik

@ -0,0 +1,204 @@
#!/usr/bin/env python
import subprocess
#import urllib as urllib
import socket
import datetime
from pprint import pprint
"""
This module is designed to fetch your external IP address from the internet.
It is used mostly when behind a NAT.
It picks your IP randomly from a serverlist to minimize request
overhead on a single server
If you want to add or remove your server from the list contact me on github
API Usage
=========
>>> import ipgetter
>>> myip = ipgetter.myip()
>>> myip
'8.8.8.8'
>>> ipgetter.IPgetter().test()
Number of servers: 47
IP's :
8.8.8.8 = 47 ocurrencies
Copyright 2014 phoemur@gmail.com
This work is free. You can redistribute it and/or modify it under the
terms of the Do What The Fuck You Want To Public License, Version 2,
as published by Sam Hocevar. See http://www.wtfpl.net/ for more details.
"""
__all__ = ['get_ip_local', 'get_ip_world']
import re
import random
from sys import version_info
PY3K = version_info >= (3, 0)
if PY3K:
import urllib.request as urllib
else:
import urllib2 as urllib
__version__ = "0.6"
class IPgetter(object):
'''
This class is designed to fetch your external IP address from the internet.
It is used mostly when behind a NAT.
It picks your IP randomly from a serverlist to minimize request overhead
on a single server
'''
def __init__(self):
self.server_list = ['http://ip.dnsexit.com',
'http://ifconfig.me/ip',
'http://ipecho.net/plain',
'http://checkip.dyndns.org/plain',
'http://ipogre.com/linux.php',
'http://whatismyipaddress.com/',
'http://ip.my-proxy.com/',
'http://websiteipaddress.com/WhatIsMyIp',
'http://getmyipaddress.org/',
'http://www.my-ip-address.net/',
'http://myexternalip.com/raw',
'http://www.canyouseeme.org/',
'http://www.trackip.net/',
'http://icanhazip.com/',
'http://www.iplocation.net/',
'http://www.howtofindmyipaddress.com/',
'http://www.ipchicken.com/',
'http://whatsmyip.net/',
'http://www.ip-adress.com/',
'http://checkmyip.com/',
'http://www.tracemyip.org/',
'http://checkmyip.net/',
'http://www.lawrencegoetz.com/programs/ipinfo/',
'http://www.findmyip.co/',
'http://ip-lookup.net/',
'http://www.dslreports.com/whois',
'http://www.mon-ip.com/en/my-ip/',
'http://www.myip.ru',
'http://ipgoat.com/',
'http://www.myipnumber.com/my-ip-address.asp',
'http://www.whatsmyipaddress.net/',
'http://formyip.com/',
'https://check.torproject.org/',
'http://www.displaymyip.com/',
'http://www.bobborst.com/tools/whatsmyip/',
'http://www.geoiptool.com/',
'https://www.whatsmydns.net/whats-my-ip-address.html',
'https://www.privateinternetaccess.com/pages/whats-my-ip/',
'http://checkip.dyndns.com/',
'http://myexternalip.com/',
'http://www.ip-adress.eu/',
'http://www.infosniper.net/',
'http://wtfismyip.com/',
'http://ipinfo.io/',
'http://httpbin.org/ip']
def get_externalip(self):
'''
This function gets your IP from a random server
'''
random.shuffle(self.server_list)
myip = ''
for server in self.server_list:
myip = self.fetch(server)
if myip != '':
return myip
else:
continue
return ''
def fetch(self, server):
'''
This function gets your IP from a specific server
'''
url = None
opener = urllib.build_opener()
opener.addheaders = [('User-agent',
"Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0")]
try:
url = opener.open(server)
content = url.read()
# Didn't want to import chardet. Prefered to stick to stdlib
if PY3K:
try:
content = content.decode('UTF-8')
except UnicodeDecodeError:
content = content.decode('ISO-8859-1')
m = re.search(
'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)',
content)
myip = m.group(0)
return myip if len(myip) > 0 else ''
except Exception:
return ''
finally:
if url:
url.close()
def test(self):
'''
This functions tests the consistency of the servers
on the list when retrieving your IP.
All results should be the same.
'''
resultdict = {}
for server in self.server_list:
resultdict.update(**{server: self.fetch(server)})
ips = sorted(resultdict.values())
ips_set = set(ips)
print('\nNumber of servers: {}'.format(len(self.server_list)))
print("IP's :")
for ip, ocorrencia in zip(ips_set, map(lambda x: ips.count(x), ips_set)):
print('{0} = {1} ocurrenc{2}'.format(ip if len(ip) > 0 else 'broken server', ocorrencia, 'y' if ocorrencia == 1 else 'ies'))
print('\n')
print(resultdict)
def get_ip_world():
try:
return IPgetter().get_externalip()
except:
return None
# Very Linux Specific
def get_ip_local():
try:
arg='ip route list'
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE, universal_newlines='\n')
data = p.communicate()
data = data[0].split('\n')
while '' in data:
data.remove('')
split_data = data[-1].split()
ipaddr = split_data[split_data.index('src')+1]
return ipaddr
except:
return None
if __name__ == '__main__':
print(get_ip_world())
print(get_ip_local())

Wyświetl plik

@ -0,0 +1,27 @@
#!/usr/bin/env python
import os
import subprocess
# generate self-signed certificate
# Very Linux Specific
def get_ip():
arg='ip route list'
p = subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE, universal_newlines=True)
data = p.communicate()
data = data[0].split('\n')
while '' in data:
data.remove('')
split_data = data[-1].split()
ipaddr = split_data[split_data.index('src')+1]
return ipaddr
def keygen():
cmd = 'openssl req -new -x509 -days 1095 -nodes -newkey rsa:2048 -out cacert.pem -keyout privkey.pem -subj "/CN={}"'
cmd = cmd.format(get_ip())
print(cmd)
os.system(cmd)
if __name__ == "__main__":
keygen()

Wyświetl plik

@ -0,0 +1,30 @@
#!/usr/bin/env python
import os
import string
import subprocess
from pprint import pprint
def get_proc():
res = []
p = subprocess.Popen("ps",stdout=subprocess.PIPE)
line = p.stdout.readline()
while line:
res.append(line)
line = p.stdout.readline()
return res
def get_dsp_id(p_arr, p_name = "habboy_data"):
for p in p_arr:
if p_name in p:
tokens = p.split()
pid = int(tokens[0])
return pid
return None
if __name__ == '__main__':
pid = get_dsp_id(get_proc())
while pid:
print(pid)
os.system('kill -9 %d' % pid)
pid = get_dsp_id(get_proc())

Wyświetl plik

@ -0,0 +1,822 @@
#!/usr/bin/env python3
import os
import sys
import time
import threading
import functools
import traceback
import argparse
from pprint import pprint
import urllib3
import subprocess
from datetime import datetime as dtime
import string
import datetime
import math
import serial
from copy import deepcopy
import psutil
import platform
import formatSentence
import HabdecClient
import HabHubClient
import HabHubInterface
import SentencesDB
import HttpInterface
import nmea
from get_ip import get_ip_local
from DummySentenceCreator import DummySentenceCreator
G_RUN = True
C_BLACK = "\033[1;30m"
C_RED = "\033[1;31m"
C_GREEN = "\033[1;32m"
C_BROWN = "\033[1;33m"
C_BLUE = "\033[1;34m"
C_MAGENTA = "\033[1;35m"
C_CYAN = "\033[1;36m"
C_LIGHTGREY = "\033[1;37m"
C_OFF = "\033[0m"
C_CLEAR = "\033[2K"
if os.name == 'nt':
C_BLACK=C_RED=C_GREEN=C_BROWN=C_BLUE=C_MAGENTA=C_CYAN=C_LIGHTGREY=C_OFF=C_CLEAR=''
# collect sentences from habitat and habdec
G_SENTENCES_DB = None
G_HABDEC_CLIENTS = {}
G_HABHUB_CLIENTS = {}
G_CLIENTS_MTX = threading.Lock()
# process statistics
G_HABBOY_STATS = {}
G_HABBOY_STATS_MTX = threading.Lock()
# flight prediction path
G_PREDICT_PATH = {}
G_PREDICT_PATH_MTX = threading.Lock()
# GPS for HABBOY/DEVICE
G_GPS_Data = {
'time': datetime.datetime.utcnow(),
'parse_timestamp': datetime.datetime.utcnow(),
"latitude": 52,
"longitude": 21,
"altitude": 100,
'heading': 0,
'ground_speed_mps': 0,
'sats': 0,
}
def get_ip():
p = subprocess.Popen("ip route list", shell=True, stdout=subprocess.PIPE)
data = p.communicate()
data = data[0].decode().split("\n")
while "" in data:
data.remove("")
split_data = data[-1].split()
ipaddr = split_data[split_data.index("src") + 1]
return ipaddr
def GpsDataFileRead(gps_data_file):
if gps_data_file:
with open(gps_data_file) as fh:
lat_lon_alt = fh.read()
sep = ',' if (',' in lat_lon_alt) else ' '
lat_lon_alt = lat_lon_alt.split('\n')
lat_lon_alt = [x.strip() for x in lat_lon_alt]
while '' in lat_lon_alt: lat_lon_alt.remove('')
lat_lon_alt = [ l.split(sep) for l in lat_lon_alt ]
lat_lon_alt = [ (float(t[1]), float(t[0]), float(t[2])) for t in lat_lon_alt]
return lat_lon_alt
def DummySentenceThreadF(i_payloadId, interval_seconds, gps_data_file):
callsign = G_SENTENCES_DB.payloadIdToCallsign(i_payloadId)
sensors_info = G_SENTENCES_DB.getSensorsInfo(i_payloadId)
lat_lon_alt = GpsDataFileRead(gps_data_file)
global G_RUN
while G_RUN:
time.sleep(interval_seconds)
lat, lon, alt = (0,0,0)
if lat_lon_alt:
lat, lon, alt = lat_lon_alt.pop(0)
s = DummySentenceCreator(i_payloadId, callsign, sensors_info, lat, lon, alt)
print(s)
G_SENTENCES_DB.insert(s, "debug")
def SentenceGatherThreadF(habdec_addr_arr, i_payload_id):
"""
collect sentences from habitat and habdec
"""
global G_HABDEC_CLIENTS
global G_HABHUB_CLIENTS
with G_CLIENTS_MTX:
for habdec_addr in habdec_addr_arr:
G_HABDEC_CLIENTS[habdec_addr] = HabdecClient.HabdecClient(
habdec_addr
) # "ws://localhost:5555"
G_HABDEC_CLIENTS[habdec_addr].Start()
G_HABHUB_CLIENTS[i_payload_id] = HabHubClient.HabHubClient(i_payload_id)
G_HABHUB_CLIENTS[i_payload_id].Start()
habdec_last_querry_time = dtime.utcnow()
habhub_last_querry_time = dtime.utcnow()
while G_RUN:
time.sleep(1)
with G_CLIENTS_MTX:
if (dtime.utcnow() - habdec_last_querry_time).total_seconds() > 1:
for habdec in G_HABDEC_CLIENTS:
HabdecClient_GetLastSentence = G_HABDEC_CLIENTS[habdec].GetLastSentence()
if HabdecClient_GetLastSentence:
print(C_RED, "Habdec: " + habdec + " ", HabdecClient_GetLastSentence, C_OFF)
G_SENTENCES_DB.insert(HabdecClient_GetLastSentence, habdec)
else:
pass
# print("habdec no last sentence")
habdec_last_querry_time = dtime.utcnow()
if (dtime.utcnow() - habhub_last_querry_time).total_seconds() > 3:
for payload_id in G_HABHUB_CLIENTS:
HabHubClient_GetLastSentence = G_HABHUB_CLIENTS[payload_id].GetLastSentence()
if HabHubClient_GetLastSentence:
print(C_MAGENTA, "HabHub: ", HabHubClient_GetLastSentence, C_OFF)
G_SENTENCES_DB.insert(HabHubClient_GetLastSentence, "habhub")
habhub_last_querry_time = dtime.utcnow()
with G_CLIENTS_MTX:
if G_HABDEC_CLIENTS:
for k, v in G_HABDEC_CLIENTS.items():
v.Stop()
G_HABDEC_CLIENTS = {}
if G_HABHUB_CLIENTS:
for k, v in G_HABHUB_CLIENTS.items():
v.Stop()
G_HABHUB_CLIENTS = {}
def GPSD_ReadThread():
try:
import gps
except ImportError:
print("No gps module")
return
session = gps.gps("localhost", "2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
global G_GPS_Data
sats = 0
while G_RUN:
try:
report = session.next()
# print(report)
if report['class'] == 'SKY':
used = [s.used for s in report.satellites]
sats = sum(used)
elif report['class'] == 'TPV':
_res = {
'time': report.time, #probably need to convert from str to datetime
"latitude": report.lat,
"longitude": report.lon,
"altitude": report.alt,
'heading': report.track,
'ground_speed_mps': report.speed,
'sats': sats
}
G_GPS_Data = _res
except KeyError:
pass
except StopIteration:
session = None
print("GPSD has terminated")
except:
# print(traceback.format_exc())
# print(report)
pass
def GPS_Serial_Thread(i_dev, line_callback):
global G_GPS_Data
nmea_parser = nmea.nmea_parser()
_ser = None
while G_RUN:
if not _ser:
try:
_ser = serial.Serial(i_dev, 115200)
except:
print(traceback.format_exc())
time.sleep(1)
continue
try:
line = _ser.readline()
except:
print(traceback.format_exc())
_ser = None
if line:
try:
if line_callback:
line_callback(line)
except:
pass
try:
nmea_data = nmea_parser.feed_line(line)
if nmea_data:
new_gps_data = {
'time': nmea_data.utc_time,
"latitude": nmea_data.lat,
"longitude": nmea_data.lon,
"altitude": nmea_data.alt,
'heading': nmea_data.heading,
'ground_speed_mps': nmea_data.ground_speed_mps,
'sats': nmea_data.sats,
'parse_timestamp': nmea_data.parse_timestamp
}
G_GPS_Data = new_gps_data
except:
print(traceback.format_exc())
def GPS_Serial_Thread_Fake():
global G_GPS_Data
while G_RUN:
new_gps_data = {
'time': datetime.datetime.utcnow(),
"latitude": 52 + .01 * math.sin(.1 * GPS_Serial_Thread_Fake.T),
"longitude": 21 + .01 * math.cos(.1 * GPS_Serial_Thread_Fake.T),
"altitude": 100,
'heading': 0,
'ground_speed_mps': 50,
'sats': 11,
'parse_timestamp': datetime.datetime.utcnow()
}
G_GPS_Data = new_gps_data
GPS_Serial_Thread_Fake.T += 1
time.sleep(1)
GPS_Serial_Thread_Fake.T = 0
def GET_HABBOY_GPS():
'''
get current HABBOY GPS
add 'fix_age' and 'data_age' fields
'''
global G_GPS_Data
gps = deepcopy(G_GPS_Data)
_now = datetime.datetime.utcnow()
gps['fix_age'] = (_now - gps['time']).total_seconds()
gps['data_age'] = (_now - gps['parse_timestamp']).total_seconds()
return gps
def get_process_stats(i_proc_name_list):
start = datetime.datetime.utcnow()
result = {}
try:
result['global'] = {}
result['global']['cpu_load_%'] = psutil.cpu_percent(interval=1)
except:
pass
try:
vmem = psutil.virtual_memory()
result['global']['mem_%'] = vmem.used / vmem.total * 100
except:
pass
try:
disk = psutil.disk_usage('/')
result['global']['disk_%'] = disk.used / disk.total * 100
except:
pass
try:
temp = psutil.sensors_temperatures()
result['global']['temp'] = 0
except:
pass
try:
result['global']['temp'] = temp['cpu_thermal'][0].current
except:
pass
# processes
procs_pid2name = {}
for proc in psutil.process_iter(['pid', 'name']):
procs_pid2name[proc.info['name']] = proc.info['pid']
result['proc'] = {}
for pname in i_proc_name_list:
if pname not in procs_pid2name:
print('not', pname)
continue
p = psutil.Process(procs_pid2name[pname])
if not p:
continue
result['proc'][pname] = {}
# result['proc'][pname]['stat'] = p.status()
result['proc'][pname]['cpu_load_%'] = p.cpu_percent(interval=1)
result['proc'][pname]['runtime'] = time.time() - p.create_time()
result['proc'][pname]['mem_MB'] = p.memory_full_info().rss / 1e6
# result['proc'][pname]['mem'] = p.memory_percent()
result['proc'][pname]['connections'] = len( p.connections() )
return result
def PROC_STATS_THREAD_F(proc_list):
global G_RUN
while G_RUN:
stats = {}
try:
stats = get_process_stats(proc_list)
except:
print(traceback.format_exc())
stats['telemetry'] = {}
stats['telemetry']['habdec'] = {}
stats['telemetry']['habhub'] = {}
global G_HABDEC_CLIENTS
global G_HABHUB_CLIENTS
global G_CLIENTS_MTX
try:
with G_CLIENTS_MTX:
now = datetime.datetime.utcnow()
for hd in G_HABDEC_CLIENTS:
stats['telemetry']['habdec'][hd] = {}
stats['telemetry']['habdec'][hd]['connection_age'] = (now - G_HABDEC_CLIENTS[hd].GetLastConnectionTime()).total_seconds()
stats['telemetry']['habdec'][hd]['sentence_age'] = (now - G_HABDEC_CLIENTS[hd].GetLastSentenceReceiveTime()).total_seconds()
for hh in G_HABHUB_CLIENTS:
stats['telemetry']['habhub'][hh] = {}
stats['telemetry']['habhub'][hh]['connection_age'] = (now - G_HABHUB_CLIENTS[hh].GetLastConnectionTime()).total_seconds()
stats['telemetry']['habhub'][hh]['sentence_age'] = (now - G_HABHUB_CLIENTS[hh].GetLastSentenceReceiveTime()).total_seconds()
except:
print(traceback.format_exc())
global G_HABBOY_STATS
global G_HABBOY_STATS_MTX
with G_HABBOY_STATS_MTX:
G_HABBOY_STATS = deepcopy(stats)
time.sleep(5)
def GET_HABBOY_STATS():
stats = {}
global G_HABBOY_STATS
global G_HABBOY_STATS_MTX
with G_HABBOY_STATS_MTX:
stats = deepcopy(G_HABBOY_STATS)
return stats
def CalcPayloadPrediction(payload_id, predictor, expected_burst):
if not predictor:
print("NO PREDICTOR")
return {}
# https://github.com/projecthorus/chasemapper/blob/master/horusmapper.py#L341
lat = G_SENTENCES_DB.getTelemetryLast(payload_id, "latitude")
lon = G_SENTENCES_DB.getTelemetryLast(payload_id, "longitude")
alt = G_SENTENCES_DB.getTelemetryLast(payload_id, "altitude")
descent_rate = 6 # default value
is_descending = False
if alt['dVdT'][-1] < 0:
descent_rate = abs(alt['dVdT'][-1])
is_descending = True
flight_path = predictor.predict(
launch_lat = lat['values'][-1],
launch_lon = lon['values'][-1],
launch_alt = max(100, alt['values'][-1]),
ascent_rate = max(3, abs(alt['dVdT'][-1])),
descent_rate = descent_rate,
burst_alt = max(alt['values'][-1]+100, expected_burst),
launch_time = datetime.datetime.utcnow(), # this better be sentence time
descent_mode = is_descending
)
return flight_path
def PREDICT_THREAD_F(payload_id, predictor, expected_burst):
global G_RUN
while G_RUN:
path = {}
try:
path = CalcPayloadPrediction(payload_id, predictor, expected_burst)
except:
print(traceback.format_exc())
global G_PREDICT_PATH
global G_PREDICT_PATH_MTX
with G_PREDICT_PATH_MTX:
G_PREDICT_PATH = deepcopy(path)
time.sleep(5)
def GetPayloadPredictPath():
global G_PREDICT_PATH
global G_PREDICT_PATH_MTX
res = {}
with G_PREDICT_PATH_MTX:
res = deepcopy(G_PREDICT_PATH)
return res
def CliArgs():
parser = argparse.ArgumentParser()
# if len(sys.argv)==1:
# parser.print_help()
# sys.exit(1)
parser.add_argument(
"--dbfile", nargs="?", type=str, const="", help="Sentences DB file"
)
parser.add_argument(
"--initDB", action='store_true', help="Create empty DB"
)
parser.add_argument(
"--updateDB", nargs="*", type=str, help="Update local DB from HABITAT. Optional args are payload_id."
)
parser.add_argument(
"--dbinfo", action="store_true", help="print payloads from local DB file"
)
parser.add_argument(
"--payloads", action="store_true", help="List flights from HABITAT"
)
parser.add_argument(
"--payload_id", type=str, default="", help="Payload ID"
)
parser.add_argument(
"--payloads_info", nargs="?", type=str, const="*", help="Show flights info from HABITAT"
)
# parser.add_argument('--callsign', nargs='?', type=str, const='*', help='callsign. if empty, deduce from payload_id')
parser.add_argument(
"--habdec",
nargs="*",
type=str,
# default=["127.0.0.1:5555"],
help="habdec WS addr. 127.0.0.1:5555",
)
parser.add_argument("--host", type=str, default = '0.0.0.0', help="hostname")
parser.add_argument( "--port", type=int, default=8888, help="http port, default 8888" )
parser.add_argument("--https", action="store_true", help="serve on https://")
parser.add_argument("--test", type=int, help="generate fake sentence every N seconds")
parser.add_argument("--test_file", type=str, help="replay GPS/alt from file. lat,lon,alt\\n")
parser.add_argument("--burst", type=int, default=30000, help="expected burst alt" )
parser.add_argument("--wind", type=str, help="NOAA wind dir")
parser.add_argument( "--hab_interval", type=int, help="Habitat query seconds interval" )
args = parser.parse_args()
return args
def CurDir():
d = os.path.dirname(sys.argv[0])
if d == '' or d == '.':
if 'PWD' in os.environ:
d = os.environ['PWD']
else:
d = os.getcwd()
return d
def HABBOY_DATA_MAIN():
os.chdir(CurDir())
args = CliArgs()
# payloads
#
payloads = []
try:
flights = HabHubInterface.getFlights()
payloads = HabHubInterface.getPayloads(flights)
if not payloads:
print("HabHub - no current payloads.")
except urllib3.exceptions.MaxRetryError:
print(C_RED, "Failed connecting to HabHub", C_OFF)
pass
# print payloads info
#
if args.payloads:
for p in payloads:
if not p["doc"]["transmissions"]:
continue
for i in range(len(p["doc"]["transmissions"])):
if p["doc"]["transmissions"][i]['modulation'].lower() != 'rtty':
continue
print(
p["doc"]["name"],
" --callsign:",
C_MAGENTA, p["doc"]["sentences"][i]["callsign"], C_OFF,
"--payload:",
C_RED, p["doc"]["_id"], C_OFF,
"--RTTY:",
C_MAGENTA, "{}/{}/{}".format(
p["doc"]["transmissions"][i]["baud"],
p["doc"]["transmissions"][i]["encoding"],
p["doc"]["transmissions"][i]["stop"] ), C_OFF,
"--freq:",
C_MAGENTA, p["doc"]["transmissions"][0]["frequency"], C_OFF,
)
return
# DB object
#
dbfile = "habboy_data.db"
if args.dbfile:
dbfile = args.dbfile
print("dbfile ", dbfile)
global G_SENTENCES_DB
G_SENTENCES_DB = SentencesDB.SentencesDB(dbfile)
# print dbinfo
#
if args.dbinfo:
info = G_SENTENCES_DB.getInfo()
for i in info:
print( C_RED, i[0], C_MAGENTA, i[1], C_OFF)
pprint(i[2:])
return
# payloads info
#
if args.payloads_info:
for p in payloads:
if args.payloads_info != "*" and p["doc"]["_id"] != args.payloads_info:
continue
print("\n")
print(C_MAGENTA, p["doc"]["name"], p["doc"]["_id"], C_OFF)
pprint(p)
print("\n")
return
if args.initDB:
print("Init DB")
G_SENTENCES_DB.create_empty()
return
if args.updateDB != None:
update_payloads = args.updateDB
if update_payloads == []:
update_payloads = [p["doc"]["_id"] for p in HabHubInterface.getPayloads()]
for pid in update_payloads:
print("Updating Info on ", pid)
G_SENTENCES_DB.updatePayloadInfo(pid)
return
# payload_id and callsign
#
payload_id = args.payload_id
if payload_id:
for p in payloads:
if p["doc"]["_id"].startswith(payload_id):
payload_id = p["doc"]["_id"]
break
print("payload_id ", payload_id)
else:
payload_id = 'NoPayload'
# print(C_RED, "No --payload_id specified. List payloads with --payloads.", C_OFF)
# return
try:
callsign_from_payload_id = HabHubInterface.getCallsignsForPayloadId(payload_id)
print("callsign from payload_id (HabHub) ", callsign_from_payload_id)
except urllib3.exceptions.MaxRetryError:
print(
C_RED,
"HabHubInterface.getCallsignsForPayloadId -- Failed connecting to HabHub",
C_OFF,
)
callsign_from_payload_id = None
if callsign_from_payload_id == None:
callsign_from_payload_id = G_SENTENCES_DB.payloadIdToCallsign(payload_id)
print("callsign from payload_id (DB) ", callsign_from_payload_id)
if callsign_from_payload_id == None:
callsign_from_payload_id = 'NoCallsign'
print(C_RED, "NO CALLSIGN", C_OFF)
# habdec addresses
#
habdec_addr_arr = []
if args.habdec:
habdec_addr_arr = args.habdec
for i in range(len(habdec_addr_arr)):
if habdec_addr_arr[i] and not habdec_addr_arr[i].startswith("ws://"):
habdec_addr_arr[i] = "ws://" + habdec_addr_arr[i]
# host and port
#
host = args.host or "0.0.0.0"
# host = args.host or get_ip()
if host.lower() == "ip":
host = get_ip()
is_https = args.https
port = args.port or 8888
# wind data
#
try:
from cusfpredict.predict import Predictor
try:
wind = args.wind or os.path.join( os.environ['HOME'], 'data/noaa_wind/gfs' )
print('Wind Dir:', wind)
predictor = Predictor(bin_path = './pred', gfs_path = wind)
except:
print(traceback.format_exc())
print("No Wind Dir")
predictor = None
except ImportError:
print("Cusf Predictor import error")
predictor = None
# some globals
#
global G_RUN
global G_HABDEC_CLIENTS
global G_HABHUB_CLIENTS
global_opts = {
'payload_id': payload_id,
'callsign': callsign_from_payload_id,
'sentences_db': G_SENTENCES_DB,
'habdec_clients': G_HABDEC_CLIENTS,
'habhub_clients': G_HABHUB_CLIENTS,
'clients_mutex': G_CLIENTS_MTX,
'payloads': G_SENTENCES_DB.getAllPayloadIds(),
'get_gps': GET_HABBOY_GPS,
'get_predict': GetPayloadPredictPath,
'get_stats': GET_HABBOY_STATS,
'burst': args.burst
}
############################ START ALL THREADS ############################
# sentence gathering thread
#
HabHubClient.HabHubClient.interval_seconds = args.hab_interval or 15
if args.test:
test_file = args.test_file or ''
sentence_gather_thread = threading.Thread(
target=functools.partial(DummySentenceThreadF, payload_id, args.test, test_file)
)
else:
sentence_gather_thread = threading.Thread(
target=functools.partial(SentenceGatherThreadF, habdec_addr_arr, payload_id)
)
sentence_gather_thread.start()
time.sleep(.25)
# http thread
#
http_server_thread = threading.Thread(
target=functools.partial(
HttpInterface.RUN,
host, port, is_https,
global_opts,
False, False,
)
)
http_server_thread.start()
time.sleep(.25)
# GPS thread
#
# gps_thread = threading.Thread(target=GPSD_ReadThread)
gps_device = '/dev/serial/by-id/usb-u-blox_AG_-_www.u-blox.com_u-blox_GNSS_receiver-if00'
gps_thread = threading.Thread( target=functools.partial(GPS_Serial_Thread, gps_device, None) )
# gps_thread = threading.Thread(target=GPS_Serial_Thread_Fake)
if os.path.isfile(gps_device):
gps_thread.start()
else:
print(gps_device, 'does not exits.')
time.sleep(.25)
# flight path predict thread
predict_thread = threading.Thread( target=functools.partial(PREDICT_THREAD_F, payload_id, predictor, args.burst) )
predict_thread.start()
# proc stats thread
#
if (platform.system() != "Windows"):
habboy_stats_thread = threading.Thread( target=functools.partial(PROC_STATS_THREAD_F, ['habboy_data', 'habdecWebsocketServer']) )
habboy_stats_thread.start()
# main loop
#
while G_RUN:
try:
time.sleep(1)
except KeyboardInterrupt:
print("\nExiting...\n")
G_RUN = False
if G_HABDEC_CLIENTS:
for k, v in G_HABDEC_CLIENTS.items():
v.Stop()
G_HABDEC_CLIENTS = {}
if G_HABHUB_CLIENTS:
for k, v in G_HABHUB_CLIENTS.items():
v.Stop()
G_HABHUB_CLIENTS = {}
# EXITING
#
if sentence_gather_thread and sentence_gather_thread.is_alive():
sentence_gather_thread.join()
if gps_thread and gps_thread.is_alive():
gps_thread.join()
if predict_thread and predict_thread.is_alive():
predict_thread.join()
if habboy_stats_thread and habboy_stats_thread.is_alive():
habboy_stats_thread.join()
def test_gps():
gps_device = '/dev/serial/by-id/usb-u-blox_AG_-_www.u-blox.com_u-blox_GNSS_receiver-if00'
gps_thread = threading.Thread( target=functools.partial(GPS_Serial_Thread, gps_device, lambda l: None) )
gps_thread.start()
if gps_thread and gps_thread.is_alive():
gps_thread.join()
if __name__ == "__main__":
try:
import setproctitle
setproctitle.setproctitle("habboy_data")
except:
print("No setproctitle")
HABBOY_DATA_MAIN()
# test_gps()

Wyświetl plik

@ -0,0 +1,237 @@
#!/usr/bin/env python3
import string
import datetime
import math
from enum import Enum
def degree_2_decimal(i_pos):
i_pos = float(i_pos)
degs = math.trunc(i_pos / 100)
mins = i_pos - 100.0 * degs
res = degs + mins / 60.0
return res
def NMEA_checksum(buff):
c = 0
for i in range(len(buff)):
c ^= ord(buff[i])
return hex(c)[2:]
class nmea_t(object):
class fix_status_t(Enum):
kInvalid = 0
kValid = 1
class fix_quality_t(Enum):
kNoFix = 0
kAutonomous = 1
kDifferential = 2
kRtkFixed = 4
kRtkFloat = 5
kEstimated = 6
def __init__(self):
self.msg = '$' # RMC or GGA
self.parse_timestamp = datetime.datetime.utcnow()
self.utc_str = ''
self.utc_time = ''
self.lat = 0.0
self.lon = 0.0
self.alt = 0.0
self.sats = 0
self.ground_speed_mps = 0.0
self.heading = 0.0
self.fix_status = nmea_t.fix_status_t( nmea_t.fix_status_t.kInvalid)
self.fix_quality = nmea_t.fix_quality_t( nmea_t.fix_quality_t.kNoFix)
def __str__(self):
res = self.msg
res += ' timestamp:' + str(self.parse_timestamp)
res += ' UTC:' + str(self.utc_time)
res += ' lat:' + str(self.lat)
res += ' lon:' + str(self.lon)
res += ' alt:' + str(self.alt)
res += ' sats:' + str(self.sats)
res += ' ground_speed_mps:' + str(self.ground_speed_mps)
res += ' heading:' + str(self.heading)
res += ' fix_status:' + str(self.fix_status)
res += ' fix_quality:' + str(self.fix_quality)
return res
def __utcstr2date__(i_utcstr):
res_utc = datetime.datetime.utcnow() # 152041.00
res_utc.replace(hour = int(i_utcstr[0:2]))
res_utc.replace(minute = int(i_utcstr[2:4]))
res_utc.replace(second = int(i_utcstr[5:6]))
microsecs = i_utcstr[8:] #after .
microsecs = int(float('0.' + microsecs) * 1000)
res_utc.replace(microsecond = microsecs) # this does not work somehow
return res_utc
class nmea_parser(object):
def __init__(self):
self.__valid_nmea__ = nmea_t()
self.__valid_nmea__.fix_status = nmea_t.fix_status_t( nmea_t.fix_status_t.kInvalid)
self.__valid_nmea__.fix_quality = nmea_t.fix_quality_t( nmea_t.fix_quality_t.kNoFix)
def feed_line(self, line):
line = line.decode('ascii').strip()
if '*' not in line:
return
while line.startswith('$'):
line = line[1:]
data_str = line[:line.index('*')]
chcksm = line[line.index('*')+1:]
if NMEA_checksum(data_str).lower() != chcksm.lower():
print("NMEA checksum fail:")
print(line)
return
nmea_current = None
if 'gga' in data_str.lower():
nmea_current = self.parse_gga(data_str)
# print(nmea_current)
elif 'rmc' in data_str.lower():
nmea_current = self.parse_rmc(data_str)
# print(nmea_current)
if nmea_current:
if nmea_current.fix_status == nmea_t.fix_status_t.kValid or nmea_current.fix_quality != nmea_t.fix_quality_t.kNoFix:
if nmea_current.msg == 'RMC':
# copy previous values from GGA type
nmea_current.alt = self.__valid_nmea__.alt
nmea_current.sats = self.__valid_nmea__.sats
elif nmea_current.msg == 'GGA':
# copy previous values from RMC type
nmea_current.ground_speed_mps = self.__valid_nmea__.ground_speed_mps
nmea_current.heading = self.__valid_nmea__.heading
# print(nmea_current)
self.__valid_nmea__ = nmea_current
return self.__valid_nmea__
def parse_gga(self, line):
'''
$GNGGA,152041.00,,,,,0,00,99.99,,,,,,*7B
GNGGA,180602.00,5206.72454,N,01957.52547,E,1,12,0.95,87.8,M,35.6,M,,*7D
return None when even UTC is not decoded
'''
res = nmea_t()
res.msg = 'GGA'
tokens = line.split(',') # should be 15 tokens
# print(tokens, len(tokens))
if len(tokens) != 15:
return
if not tokens[1]:
return
else:
res.utc_str = tokens[1]
res.utc_time = __utcstr2date__(res.utc_str)
if(not tokens[2]):
return res
else:
res.lat = degree_2_decimal(tokens[2])
if tokens[3].lower() == 's':
res.lat = -res.lat
if(not tokens[4]):
return res
else:
res.lon = degree_2_decimal(tokens[4])
if tokens[5].lower() == 'w':
res.lon = -res.lon
quality = tokens[6]
if not quality:
return res
else:
quality = int(quality)
if quality == 0:
res.fix_quality = nmea_t.fix_quality_t.kNoFix
if quality == 1:
res.fix_quality = nmea_t.fix_quality_t.kAutonomous
if quality == 2:
res.fix_quality = nmea_t.fix_quality_t.kDifferential
if quality == 4:
res.fix_quality = nmea_t.fix_quality_t.kRtkFixed
if quality == 5:
res.fix_quality = nmea_t.fix_quality_t.kRtkFloat
if quality == 6:
res.fix_quality = nmea_t.fix_quality_t.kEstimated
if not tokens[7]:
return res
else:
res.sats = int(tokens[7])
if not tokens[9]:
return res
else:
res.alt = float(tokens[9])
return res
def parse_rmc(self, line):
'''
$GNRMC,154248.00,V,,,,,,,010620,,,N*68
GNRMC,180602.00,A,5206.72454,N,01957.52547,E,0.023,,010620,,,A*6D
return None when even UTC is not decoded
'''
res = nmea_t()
res.msg = 'RMC'
tokens = line.split(',') # should be 13 tokens
# print(tokens, len(tokens))
if len(tokens) != 13:
return
if not tokens[1]:
return
else:
res.utc_str = tokens[1]
res.utc_time = __utcstr2date__(res.utc_str)
if not tokens[2]:
return res
else:
if tokens[2].lower() == 'a':
res.fix_status = nmea_t.fix_status_t.kValid
elif tokens[2].lower() == 'v':
res.fix_status = nmea_t.fix_status_t.kInvalid
if(not tokens[3]):
return res
else:
res.lat = degree_2_decimal(tokens[3])
if tokens[4].lower() == 's':
res.lat = -res.lat
if(not tokens[5]):
return res
else:
res.lon = degree_2_decimal(tokens[5])
if tokens[6].lower() == 'w':
res.lon = -res.lon
if not tokens[7]:
res.ground_speed_mps = 0
else:
res.ground_speed_mps = 0.514444444 * float(tokens[7]) # from knots to m/s
if not tokens[8]:
res.heading = 0
else:
res.heading = float(tokens[8])
return res

Wyświetl plik

@ -0,0 +1,4 @@
# Discovery
Tools to help find Habdec/habboy in a network without DNS and static IPs.
[discovery - Install As Service](./lan/README.md)

Wyświetl plik

@ -0,0 +1,7 @@
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: text/plain");
$ip = file_get_contents($_GET["HOST"]);
$ip = strip_tags($ip);
echo $ip;
?>

Wyświetl plik

@ -0,0 +1,29 @@
<!-- rename this file to index.html and put on some website -->
<!-- index.html will scan local network IPs to find discovery/lan/HabBoyAdvertise.py -->
<html>
<body>
<script>
function get_server_ip(i_srv_name) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.cgarea.com/ip/get.php?HOST=' + i_srv_name);
xhr.onload = function() {
if (xhr.status === 200) {
var local_ip = xhr.responseText.split("|")[2];
window.location.replace('https://' + local_ip + ':8888');
}
else
console.debug(xhr.responseTex);
};
xhr.send();
}
document.addEventListener(
"DOMContentLoaded",
() => { get_server_ip("habboy"); }
);
</script>
</body>
</html>

Wyświetl plik

@ -0,0 +1,4 @@
{
"habboy": "2019-10-16|22:00:01.379700|192.168.1.53|83.238.169.175",
"pi1": "2019-10-16|21:57:03.096608|192.168.1.12|83.238.169.175"
}

Wyświetl plik

@ -0,0 +1,15 @@
<html>
<body>
<?php
$host = $_GET["HOST"];
$ip = $_GET["IP"];
file_put_contents($host, $ip);
$ips_str = file_get_contents("ip.json");
$ips_str = strip_tags($ips_str);
$ips = json_decode($ips_str, true);
$ips[$host] = $ip;
file_put_contents( "ip.json", json_encode($ips) );
?>
</body>
</html>

Wyświetl plik

@ -0,0 +1,199 @@
#!/usr/bin/env python
import string
import subprocess
import socket
import datetime
import re
import random
from sys import version_info
PY3K = version_info >= (3, 0)
if PY3K:
import urllib.request as urllib
else:
import urllib2 as urllib
__version__ = "0.6"
def myip():
return IPgetter().get_externalip()
class IPgetter(object):
'''
This class is designed to fetch your external IP address from the internet.
It is used mostly when behind a NAT.
It picks your IP randomly from a serverlist to minimize request overhead
on a single server
'''
def __init__(self):
self.server_list = ['http://ip.dnsexit.com',
'http://ifconfig.me/ip',
'http://ipecho.net/plain',
'http://checkip.dyndns.org/plain',
'http://ipogre.com/linux.php',
'http://whatismyipaddress.com/',
'http://ip.my-proxy.com/',
'http://websiteipaddress.com/WhatIsMyIp',
'http://getmyipaddress.org/',
'http://www.my-ip-address.net/',
'http://myexternalip.com/raw',
'http://www.canyouseeme.org/',
'http://www.trackip.net/',
'http://icanhazip.com/',
'http://www.iplocation.net/',
'http://www.howtofindmyipaddress.com/',
'http://www.ipchicken.com/',
'http://whatsmyip.net/',
'http://www.ip-adress.com/',
'http://checkmyip.com/',
'http://www.tracemyip.org/',
'http://checkmyip.net/',
'http://www.lawrencegoetz.com/programs/ipinfo/',
'http://www.findmyip.co/',
'http://ip-lookup.net/',
'http://www.dslreports.com/whois',
'http://www.mon-ip.com/en/my-ip/',
'http://www.myip.ru',
'http://ipgoat.com/',
'http://www.myipnumber.com/my-ip-address.asp',
'http://www.whatsmyipaddress.net/',
'http://formyip.com/',
'https://check.torproject.org/',
'http://www.displaymyip.com/',
'http://www.bobborst.com/tools/whatsmyip/',
'http://www.geoiptool.com/',
'https://www.whatsmydns.net/whats-my-ip-address.html',
'https://www.privateinternetaccess.com/pages/whats-my-ip/',
'http://checkip.dyndns.com/',
'http://myexternalip.com/',
'http://www.ip-adress.eu/',
'http://www.infosniper.net/',
'http://wtfismyip.com/',
'http://ipinfo.io/',
'http://httpbin.org/ip']
def get_externalip(self):
'''
This function gets your IP from a random server
'''
random.shuffle(self.server_list)
myip = ''
for server in self.server_list:
myip = self.fetch(server)
if myip != '':
return myip
else:
continue
return ''
def fetch(self, server):
'''
This function gets your IP from a specific server
'''
url = None
opener = urllib.build_opener()
opener.addheaders = [('User-agent',
"Mozilla/5.0 (X11; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0")]
try:
url = opener.open(server)
content = url.read()
# Didn't want to import chardet. Prefered to stick to stdlib
if PY3K:
try:
content = content.decode('UTF-8')
except UnicodeDecodeError:
content = content.decode('ISO-8859-1')
m = re.search(
'(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)',
content)
myip = m.group(0)
return myip if len(myip) > 0 else ''
except Exception:
return ''
finally:
if url:
url.close()
def test(self):
'''
This functions tests the consistency of the servers
on the list when retrieving your IP.
All results should be the same.
'''
resultdict = {}
for server in self.server_list:
resultdict.update(**{server: self.fetch(server)})
ips = sorted(resultdict.values())
ips_set = set(ips)
print('\nNumber of servers: {}'.format(len(self.server_list)))
print("IP's :")
for ip, ocorrencia in zip(ips_set, map(lambda x: ips.count(x), ips_set)):
print('{0} = {1} ocurrenc{2}'.format(ip if len(ip) > 0 else 'broken server', ocorrencia, 'y' if ocorrencia == 1 else 'ies'))
print('\n')
print(resultdict)
# Change to your own account information
# Very Linux Specific
def get_ip():
arg='ip route list'
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate()
split_data = data[0].split()
ipaddr = split_data[split_data.index('src')+1]
return ipaddr
def get_local_ips():
arg='ip route list'
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE)
data = p.communicate()
split_data = data[0].split()
# ipaddr = split_data[split_data.index('src')+1]
res = []
for i in xrange(len(split_data)):
if split_data[i] == 'src':
res.append(split_data[i+1])
return res
def send_to_www(IP):
H = socket.gethostname()
url = 'http://cgarea.com/ip/ip.php?HOST=%s&IP=%s' % (H, IP)
print url
hdr = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, sdch',
'Accept-Language': 'pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
}
req = urllib.Request(url, headers = hdr)
urllib.urlopen( req )
if __name__ == '__main__':
ip = str( datetime.datetime.now() ).replace(' ', '|')
# ip += '|' + get_ip()
ip += '|' + string.join( get_local_ips(), '|')
ip += '|' + myip()
try:
send_to_www(ip)
except:
import traceback
print traceback.format_exc()
pass
print ip

Wyświetl plik

@ -0,0 +1,77 @@
#!/usr/bin/env python3
__all__ = ['RUN']
import argparse
import subprocess
import bottle
HELP_STRING = r'''HabBoyAdvertise
Simple HTTP server running on port 8889
Answers on "/habboy" URL and redirects to true HabBoy server
This is usefull if HabBoy runs on HTTPS and can't respond to HTTP requests
'''
def get_ip():
p = subprocess.Popen("ip route list", shell=True, stdout=subprocess.PIPE)
data = p.communicate()
data = data[0].decode().split("\n")
while "" in data:
data.remove("")
split_data = data[-1].split()
ipaddr = split_data[split_data.index("src") + 1]
return ipaddr
class EnableCors(object):
name = "enable_cors"
api = 2
def apply(self, fn, context):
def _enable_cors(*args, **kwargs):
# set CORS headers
bottle.response.headers["Access-Control-Allow-Origin"] = "*"
bottle.response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, OPTIONS"
bottle.response.headers["Access-Control-Allow-Headers"] = "Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token"
# actual request; reply with the actual response
if bottle.request.method != "OPTIONS":
return fn(*args, **kwargs)
return _enable_cors
application = bottle.app()
application.install(EnableCors())
# @application.route('/')
@application.route('/habboy')
def route_root():
new_url = bottle.request.url[0:bottle.request.url.rindex(':')]
new_port = '8888'
res = '<meta http-equiv="refresh" content="0; url={}:{}" />'.format(new_url, new_port)
return res
def RUN(host,port):
bottle.run(host=host, port=port, debug=False, reloader=False)
print(host,port)
def main():
try:
import setproctitle
setproctitle.setproctitle("HabBoyAdvertise")
except:
print("No setproctitle")
parser = argparse.ArgumentParser()
parser.add_argument("--host", type=str, default="0.0.0.0", help="hostname")
parser.add_argument("--port", type=int, default=8889, help="http port, default 8889")
args = parser.parse_args()
RUN(host=args.host, port=args.port)
if __name__ == "__main__":
main()

Wyświetl plik

@ -0,0 +1,157 @@
#!/usr/bin/env python3
import sys
import subprocess
import socket
import urllib3
import traceback
import argparse
import time
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
__all__ = ['habboy_discovery', 'is_habboy', 'get_ip', 'ip_increment']
HELP_STRING = r'''
HabBoy Discovery
Attempts to find running HabBoy server in local network.
Loop over IP addresses starting from start_IP.
Probes for Habboy or HabboyAdvertise server on port 8888 or 8889
If not found, increments IP address and scans again.
'''
def get_ip_old():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1)) # doesn't even have to be reachable
IP = s.getsockname()[0]
except:
IP = None
finally:
s.close()
return IP
def get_ip():
try:
arg='ip route list'
p=subprocess.Popen(arg,shell=True,stdout=subprocess.PIPE, universal_newlines='\n')
data = p.communicate()
data = data[0].split('\n')
while '' in data:
data.remove('')
split_data = data[-1].split()
ipaddr = split_data[split_data.index('src')+1]
return ipaddr
except:
return None
def ip_increment(i_ip):
tokens = i_ip.split('.')
tokens[3] = int(tokens[3]) + 1
if tokens[3] > 254:
return ""
# do not increment to next network
'''
tokens[3] = 2
tokens[2] = int(tokens[2]) + 1
if tokens[2] > 254:
return ""
'''
tokens = map(str, tokens)
return '.'.join(tokens)
def test_ip_increment(i_ip):
ip = i_ip
while ip != "":
# print(ip)
ip = ip_increment(ip)
return ""
def is_habboy(i_url, timeout_ms = 2000):
timeout_ms = timeout_ms or 2000
try:
try:
r = http.request('GET', 'http://' + i_url, timeout=.001 * timeout_ms)
except urllib3.exceptions.MaxRetryError:
r = http.request('GET', 'https://' + i_url, timeout=.001 * timeout_ms)
except KeyboardInterrupt:
sys.exit(0)
except:
return False
if r.status == 200:
return True
return False
def habboy_discovery(start_ip = '', port = 8888, timeout_ms = None, verbose = False):
while not start_ip:
start_ip = get_ip()
if start_ip:
start_ip = start_ip.split('.')
start_ip[-1] = '2'
start_ip = '.'.join(start_ip)
break
time.sleep(1)
ip = start_ip
while True:
if not ip:
break
_url = '{}:{}/habboy'.format(ip, port)
if verbose:
print(_url)
if is_habboy(_url, timeout_ms):
return ip
ip = ip_increment(ip)
return None
def CliArgs():
parser = argparse.ArgumentParser()
parser.add_argument("--start_ip", type=str, default="", help="Scan for HabBoy/HabBoyAdvertise server starting from IP upwards.")
parser.add_argument("--port", type=int, default=8888, help="habboy discovery port. 8888 or 8889. default 8888.")
parser.add_argument("--timeout_ms", type=int, help="probing timeout milliseconds")
parser.add_argument("--verbose", action="store_true", help="print IPs")
args = parser.parse_args()
return args
def main():
args = CliArgs()
start_ip = args.start_ip
port = args.port
verbose = args.verbose
timeout = args.timeout_ms
try:
while(True):
res = habboy_discovery(start_ip = start_ip, port=port, verbose = verbose, timeout_ms = timeout)
if verbose:
print(res)
if res:
print(res)
sys.exit(0)
except KeyboardInterrupt:
sys.exit(0)
if __name__ == "__main__":
main()

Wyświetl plik

@ -0,0 +1,104 @@
#!/usr/bin/env python3
'''
find habboy
and periodically add habdec to it
'''
import time
import argparse
import traceback
import urllib3
http = urllib3.PoolManager(cert_reqs='CERT_NONE')
import HabBoyDiscovery
HELP_STRING = r'''HabDecAdvertise
Loops over IP range to find running HabBoy server and inform it that habdec is running.
Parameters:
--start_ip - scan for habboy from this address upward
--disco_port - probe habboy on discovery port. 8888 if HabBoy works over HTTP or 8889 for HTTPS
--habboy_port - port on which habboy runs
--timeout_ms
--pause
--verbose
Habdec IP = habboy IP
Habdec port = 5555
'''
def RegisterHabDec(habboy_ip, habboy_port='8888', habdec_ip = None, habdec_port='5555' ):
while not habdec_ip:
habdec_ip = HabBoyDiscovery.get_ip()
_url = '{}:{}/habboy/api/v1/habdec/add/{}:{}'.format(
habboy_ip, habboy_port, habdec_ip, habdec_port
)
# print (_url)
try:
r = http.request('GET', 'http://' + _url)
except urllib3.exceptions.MaxRetryError:
try:
r = http.request('GET', 'https://' + _url)
except:
return False
if r.status == 200:
# print(r.data)
return r.data == b'OK' or r.data == b'already exists'
else:
# print(r)
return False
def RegisterHabDecLoop(i_start_ip, disco_port, habboy_port, pause = 1, timeout_ms = None, verbose=0):
while True:
try:
habboy_ip = HabBoyDiscovery.habboy_discovery(start_ip = i_start_ip, port = disco_port, verbose = verbose, timeout_ms = timeout_ms)
if habboy_ip:
res = RegisterHabDec(habboy_ip, habboy_port)
if verbose:
print(habboy_ip, res)
except:
# print("Connection Error")
print(traceback.format_exc())
pass
time.sleep(pause)
def test():
habboy_ip = HabBoyDiscovery.habboy_discovery('192.168.2.170')
print('habboy_ip: ', habboy_ip)
print( RegisterHabDec(habboy_ip) )
def CliArgs():
parser = argparse.ArgumentParser()
parser.add_argument("--start_ip", type=str, default="", help="Scan for HabBoy starting from this IP upward.")
parser.add_argument("--disco_port", type=int, default=8888, help="Probe habboy on discovery port. 8888 for HTTP or 8889 for HTTPS. Default 8888.")
parser.add_argument("--habboy_port", type=int, default=8888, help="habboy server port. Default 8888.")
parser.add_argument("--timeout_ms", type=int, help="Probing timeout milliseconds")
parser.add_argument("--pause", type=int, default=15, help="Looping interval pause")
parser.add_argument("--verbose", action="store_true", help="Print IPs")
args = parser.parse_args()
return args
def main():
try:
import setproctitle
setproctitle.setproctitle("HabDecAdvertise")
except:
print("No setproctitle")
print(HELP_STRING)
args = CliArgs()
timeout_ms = args.timeout_ms
RegisterHabDecLoop( args.start_ip, args.disco_port, args.habboy_port, args.pause, timeout_ms, args.verbose )
if __name__ == "__main__":
main()

Wyświetl plik

@ -0,0 +1,42 @@
### HabDecAdvertise.py
HabDec Advertise
Loops over IP range to find running HabBoy server and inform it that habdec is running.
Parameters:
--start_ip - scan for habboy from this address upward
--disco_port - probe habboy on discovery port. 8888 if HabBoy works over HTTP or 8889 for HTTPS
--habboy_port - port on which habboy runs
--timeout_ms
--pause
--verbose
Habdec IP = habboy IP
Habdec port = 5555
### HabBoyAdvertise.py
HabBoy Advertise
Simple HTTP server running on port 8889
Answers on "/habboy" URL and redirects to true HabBoy server
This is usefull if HabBoy runs on HTTPS and can't respond to HTTP requests
##### HabBoy Advertise - Install As Service
sudo cp ./discovery/lan/HabBoyAdvertise.service /etc/systemd/system/
sudo systemctl enable HabBoyAdvertise.service
sudo systemctl daemon-reload
sudo systemctl start HabBoyAdvertise.service
sudo journalctl -u HabBoyAdvertise.service
Open index.html in browser - it will find HabBoy in your LAN
### HabBoyDiscovery.py
HabBoy Discovery
Attempts to find running HabBoy server in local network.
Loop over IP addresses starting from start_IP.
Probes for Habboy or HabboyAdvertise server on port 8888 or 8889
If not found, increments IP address and scans again.
### index.html
Scans over IP range looking for running HabBoy server.
Probes http://IP:8888/habboy
This is javascript equvalent of HabBoyDiscovery.py
URL parameter: ip - scan from this IP upwards HabBoyDiscovery.py
For example: http://index.html?ip=192.168.88.235

Wyświetl plik

@ -0,0 +1,14 @@
[Unit]
Description=habboy
Wants=network.target network-online.target
After=network.target network-online.target
[Service]
#Type=simple
User=mfratczak
Group=mfratczak
ExecStart=/home/mfratczak/share/dev/habboy_dev/habboy_sw/data_server/code/main.py
WorkingDirectory=/home/mfratczak/share/dev/habboy_dev/habboy_sw/data_server/code/
[Install]
WantedBy=multi-user.target

Wyświetl plik

@ -0,0 +1,14 @@
[Unit]
Description=habboy_advertise
Wants=network.target network-online.target
After=network.target network-online.target
[Service]
#Type=simple
User=mfratczak
Group=mfratczak
ExecStart=/home/mfratczak/share/dev/habboy_dev/habboy_sw/discovery/lan/HabBoyAdvertise.py
WorkingDirectory=/home/mfratczak/share/dev/habboy_dev/habboy_sw/discovery/lan
[Install]
WantedBy=multi-user.target

Wyświetl plik

@ -0,0 +1,15 @@
[Unit]
Description=habdec
Wants=network.target network-online.target
After=network.target network-online.target
[Service]
#Type=simple
User=mfratczak
Group=mfratczak
ExecStart=/home/mfratczak/share/dev/habdec/build/install/habdecWebsocketServer --config service.config --print 0 --no_exit 1
WorkingDirectory=/home/mfratczak/share/dev/habdec/build/install/
Restart=on-failure
[Install]
WantedBy=multi-user.target

Wyświetl plik

@ -0,0 +1,14 @@
[Unit]
Description=habdec_advertise
Wants=network.target network-online.target
After=network.target network-online.target
[Service]
#Type=simple
User=mfratczak
Group=mfratczak
ExecStart=/home/mfratczak/share/dev/habboy_dev/habboy_sw/discovery/lan/HabDecAdvertise.py --start_ip 192.168.1.240 --timeout_ms 500 --verbose
[Install]
WantedBy=multi-user.target

Wyświetl plik

@ -0,0 +1,92 @@
<!-- Scan all IP addresses for HabBoy server -->
<html>
<body bgcolor='black'>
<H1 style='color: white'>
Scanning network for HABBOY
<div id='HABBOY_DIV'></div>
</H1>
<script>
function ip_increment(i_ip) {
var tokens = i_ip.split('.');
tokens[3] = parseInt(tokens[3]) + 1;
if (tokens[3] > 254) {
return "";
// do not increment to next network
/*
tokens[3] = 2;
tokens[2] = parseInt(tokens[2]) + 1;
if (tokens[2] > 254)
return "";
*/
}
return tokens.join('.');
}
var start_ip = "";
var habboy_port = "8888";
var probe_port = "8888";
// var probe_port = "8889";
var habboy_protocol = 'https://';
var probe_protocol = 'http://';
// var probe_protocol = 'https://'; // discovery won't work with https - you need to mark page as secure
function habboy_discovery(i_ip) {
document.getElementById("HABBOY_DIV").innerHTML = i_ip;
let probe_end_point = probe_protocol + i_ip + ':' + probe_port + '/habboy';
console.debug(probe_end_point);
let xhr = new XMLHttpRequest();
xhr.timeout = 500;
xhr.open('GET', probe_end_point);
xhr.onreadystatechange = function () {
if (xhr.status === 200) {
let _destination = habboy_protocol + i_ip + ':' + habboy_port + '/';
document.getElementById("HABBOY_DIV").innerHTML = "<a href=" + _destination + '>' + _destination + "</a>";
window.location.replace(_destination);
}
else {
console.debug(xhr.status);
let incr_ip = ip_increment(i_ip);
if(incr_ip == '') {
habboy_discovery(start_ip); //restart
}
else {
habboy_discovery(incr_ip); //restart
}
}
};
xhr.send();
}
function test(i_ip) { // test IP incrementation
let ip = i_ip;
while (ip != "") {
console.debug(ip);
ip = ip_increment(ip);
}
}
document.addEventListener(
"DOMContentLoaded",
() => {
const urlParams = new URLSearchParams(window.location.search);
start_ip = urlParams.get('ip');
if(!start_ip)
start_ip = "192.168.1.2";
habboy_discovery(start_ip);
// () => { test("192.168.252.2");
}
);
</script>
</body>
</html>

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 134 KiB

BIN
docs/HabBoy_Osm.jpg 100644

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 183 KiB

Wyświetl plik

@ -0,0 +1,14 @@
# OpenStreetMap Vector Tiles
![](./HabBoy_Osm.jpg)
To use Open Street Map in HabBoy, you need to generate vector tiles in MapBox format. It is recommended to use [tilemaker](https://github.com/systemed/tilemaker).
You can use [this repo](https://github.com/ogre/tilemaker_config) as guideline to tilemaker configuration and usage.
Folder ```tilemaker_config``` in this repo contains tilemaker configuration for HabBoy.
After successful generation of tiles, symlink tiles folder to correct webserver location. The exact URL at which tiles must be accesible is defined in file ```webUI/code/js/HB_map_style_default.js``` in ```var data_root = HABBOY_URL + "/osm/tiles";```.
For example:
```ln -s ~/osm /var/www/html/osm```

Wyświetl plik

@ -0,0 +1,164 @@
<mxfile>
<diagram id="kVDm_knLuPEapHOvSkhW" name="Page-1">
<mxGraphModel dx="925" dy="764" grid="1" gridSize="10" guides="1" tooltips="1" connect="1" arrows="1" fold="1" page="1" pageScale="1" pageWidth="850" pageHeight="1100" math="0" shadow="0">
<root>
<mxCell id="0"/>
<mxCell id="1" parent="0"/>
<mxCell id="12" value="" style="whiteSpace=wrap;html=1;strokeColor=#314354;opacity=50;shadow=0;sketch=0;glass=0;fillColor=#353E47;labelPosition=center;verticalLabelPosition=top;align=center;verticalAlign=bottom;fontStyle=1;fontColor=#FF0000;rounded=1;" parent="1" vertex="1">
<mxGeometry x="510" y="120" width="340" height="470" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-16" value="" style="whiteSpace=wrap;html=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="30" y="760" width="290" height="270" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-27" value="&lt;div&gt;&lt;font color=&quot;#CC0000&quot;&gt;WEBSOCKET&lt;/font&gt;&lt;/div&gt;&lt;div&gt;- COMMAND &amp;amp; GUI&lt;/div&gt;" style="edgeStyle=none;comic=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=1;exitDx=0;exitDy=0;entryX=0.75;entryY=0;entryDx=0;entryDy=0;shadow=0;startArrow=classic;startFill=1;strokeColor=#000000;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-1" target="ChM7FxRyLafK2Ug-lwnD-3" edge="1">
<mxGeometry x="0.625" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-30" value="&lt;div&gt;&lt;font color=&quot;#CC0000&quot;&gt;WEBSOCKET&lt;/font&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;- PAYLOAD SENTENCES&lt;br&gt;&lt;/div&gt;" style="edgeStyle=none;comic=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.25;exitY=1;exitDx=0;exitDy=0;shadow=0;startArrow=classic;startFill=1;strokeColor=#000000;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-1" target="ChM7FxRyLafK2Ug-lwnD-2" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-1" value="&lt;div&gt;&lt;font color=&quot;#3333FF&quot;&gt;HABDEC&lt;/font&gt;&lt;/div&gt;" style="whiteSpace=wrap;html=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="370" y="150" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-25" value="&lt;div&gt;&lt;font color=&quot;#CC0000&quot;&gt;HTTP REST&lt;/font&gt;&lt;/div&gt;&lt;div&gt;- PAYLOAD DATA&lt;br&gt;&lt;/div&gt;&lt;div&gt;- HabBoy GPS&lt;/div&gt;" style="edgeStyle=none;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;entryX=0;entryY=0.25;entryDx=0;entryDy=0;startArrow=classic;startFill=1;strokeColor=#000000;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-2" target="ChM7FxRyLafK2Ug-lwnD-3" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="5" style="orthogonalLoop=1;jettySize=auto;html=1;exitX=0.75;exitY=0;exitDx=0;exitDy=0;strokeColor=#000000;startArrow=classic;startFill=1;endArrow=none;endFill=0;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-2" target="3" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="6" value="&lt;font color=&quot;#ff0000&quot;&gt;HTTP REST&lt;br&gt;&lt;/font&gt;- PAYLOAD SENTENCES&lt;font color=&quot;#ff0000&quot;&gt;&lt;br&gt;&lt;/font&gt;" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];rounded=1;" parent="5" vertex="1" connectable="0">
<mxGeometry x="-0.2415" y="1" relative="1" as="geometry">
<mxPoint x="2.6499999999999986" y="-81.99" as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-2" value="&lt;div&gt;&lt;font color=&quot;#3333FF&quot;&gt;DATASERVER&lt;br&gt;&lt;/font&gt;&lt;/div&gt;" style="whiteSpace=wrap;html=1;align=right;rounded=1;" parent="1" vertex="1">
<mxGeometry x="40" y="390" width="170" height="100" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-3" value="&lt;div&gt;&lt;font color=&quot;#3333FF&quot;&gt;WEB UI&lt;/font&gt;&lt;/div&gt;" style="whiteSpace=wrap;html=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="340" y="530" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-4" value="&lt;div&gt;&lt;font color=&quot;#3333FF&quot;&gt;HW IFACE&lt;/font&gt;&lt;/div&gt;" style="whiteSpace=wrap;html=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="710" y="510" width="120" height="60" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-9" value="&lt;div&gt;&lt;font color=&quot;#CC0000&quot;&gt;SERIAL&lt;/font&gt;&lt;/div&gt;&lt;div&gt;- GPS, BUTTONS, COMPASS&lt;br&gt;&lt;/div&gt;" style="orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0;exitDx=70;exitDy=80;exitPerimeter=0;strokeColor=#000000;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-6" target="ChM7FxRyLafK2Ug-lwnD-4" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-6" value="ARDUINO" style="shape=cube;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;darkOpacity=0.05;darkOpacity2=0.1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="700" y="310" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-7" value="SQLITE" style="shape=cylinder;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="60" y="400" width="60" height="80" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-10" value="&lt;div&gt;&lt;font color=&quot;#CC0000&quot;&gt;WEBSOCKET&lt;/font&gt;&lt;/div&gt;&lt;div&gt;- GPS, BUTTONS, COMPASS&lt;/div&gt;" style="endArrow=classic;startArrow=classic;html=1;entryX=0;entryY=0.5;entryDx=0;entryDy=0;exitX=1;exitY=0.25;exitDx=0;exitDy=0;strokeColor=#000000;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-3" target="ChM7FxRyLafK2Ug-lwnD-4" edge="1">
<mxGeometry x="0.2019" y="12" width="50" height="50" relative="1" as="geometry">
<mxPoint x="130" y="600" as="sourcePoint"/>
<mxPoint x="180" y="550" as="targetPoint"/>
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-11" value="&lt;div&gt;BUTTONS&lt;/div&gt;&lt;div&gt;&amp;amp;&lt;/div&gt;&lt;div&gt;JOYSTICK&lt;br&gt;&lt;/div&gt;" style="shape=cube;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;darkOpacity=0.05;darkOpacity2=0.1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="530" y="160" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-12" value="GPS" style="shape=cube;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;darkOpacity=0.05;darkOpacity2=0.1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="700" y="160" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-19" value="&lt;font color=&quot;#CC0000&quot;&gt;GPIO PINS&lt;/font&gt;" style="endArrow=classic;startArrow=none;html=1;startFill=0;entryX=0.25;entryY=0;entryDx=0;entryDy=0;entryPerimeter=0;strokeColor=#000000;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-11" target="ChM7FxRyLafK2Ug-lwnD-6" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="180" y="610" as="sourcePoint"/>
<mxPoint x="130" y="660" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-20" value="&lt;font color=&quot;#CC0000&quot;&gt;I2C&lt;/font&gt;" style="endArrow=classic;startArrow=classic;html=1;entryX=0.508;entryY=1.05;entryDx=0;entryDy=0;entryPerimeter=0;strokeColor=#000000;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-6" target="ChM7FxRyLafK2Ug-lwnD-12" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="750" y="280" as="sourcePoint"/>
<mxPoint x="710" y="210" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-24" value="&lt;div&gt;&lt;font color=&quot;#CC0000&quot;&gt;HTTP&lt;/font&gt;&lt;/div&gt;&lt;div&gt;- MAP&lt;br&gt;&lt;/div&gt;" style="edgeStyle=none;orthogonalLoop=1;jettySize=auto;html=1;exitX=1;exitY=0.5;exitDx=0;exitDy=0;strokeColor=#000000;shadow=0;comic=0;startArrow=classic;startFill=1;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-22" target="ChM7FxRyLafK2Ug-lwnD-3" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-22" value="APACHE" style="whiteSpace=wrap;html=1;align=right;rounded=1;" parent="1" vertex="1">
<mxGeometry x="40" y="510" width="170" height="100" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-21" value="&lt;div&gt;OSM&lt;/div&gt;&lt;div&gt;TILES&lt;br&gt;&lt;/div&gt;" style="shape=cylinder;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="60" y="520" width="60" height="80" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-32" value="&lt;div&gt;&lt;font color=&quot;#CC0000&quot;&gt;HTTP&lt;/font&gt;&lt;br&gt;&lt;/div&gt;&lt;div&gt;- PAYLOAD TELEMETRY&lt;br&gt;&lt;/div&gt;" style="edgeStyle=none;comic=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.55;exitY=0.95;exitDx=0;exitDy=0;exitPerimeter=0;entryX=0.25;entryY=0;entryDx=0;entryDy=0;shadow=0;startArrow=classic;startFill=1;strokeColor=#000000;" parent="1" source="ChM7FxRyLafK2Ug-lwnD-31" target="ChM7FxRyLafK2Ug-lwnD-2" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="ChM7FxRyLafK2Ug-lwnD-31" value="HAB HUB" style="ellipse;shape=cloud;whiteSpace=wrap;html=1;align=center;rounded=1;" parent="1" vertex="1">
<mxGeometry x="19" y="240" width="120" height="80" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-1" value="&lt;font style=&quot;font-size: 18px&quot;&gt;&lt;i&gt;Legend&lt;/i&gt;&lt;/font&gt;" style="text;html=1;resizable=0;points=[];autosize=1;align=left;verticalAlign=top;spacingTop=-4;rounded=1;" parent="1" vertex="1">
<mxGeometry x="49" y="784" width="90" height="20" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-2" value="&lt;font color=&quot;#3333FF&quot;&gt;WEB UI&lt;/font&gt;" style="whiteSpace=wrap;html=1;align=right;rounded=1;" parent="1" vertex="1">
<mxGeometry x="50" y="820" width="70" height="20" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-3" value="HabBoy Software Component" style="text;html=1;resizable=0;points=[];autosize=1;align=left;verticalAlign=top;spacingTop=-4;rounded=1;" parent="1" vertex="1">
<mxGeometry x="130" y="820" width="170" height="10" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-4" value="" style="ellipse;shape=cloud;whiteSpace=wrap;html=1;align=center;rounded=1;" parent="1" vertex="1">
<mxGeometry x="50" y="847" width="70" height="33" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-5" value="Internet Resource" style="text;html=1;resizable=0;points=[];autosize=1;align=left;verticalAlign=top;spacingTop=-4;rounded=1;" parent="1" vertex="1">
<mxGeometry x="130" y="853.5" width="130" height="20" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-6" value="" style="shape=cylinder;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="50" y="890" width="65" height="30" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-7" value="Disk Data Files" style="text;html=1;resizable=0;points=[];autosize=1;align=left;verticalAlign=top;spacingTop=-4;rounded=1;" parent="1" vertex="1">
<mxGeometry x="130" y="890" width="110" height="20" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-8" value="" style="shape=cube;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;darkOpacity=0.05;darkOpacity2=0.1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="50" y="942" width="60" height="38" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-9" value="Hardware Element" style="text;html=1;resizable=0;points=[];autosize=1;align=left;verticalAlign=top;spacingTop=-4;rounded=1;" parent="1" vertex="1">
<mxGeometry x="128" y="956" width="130" height="20" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-14" value="&lt;font color=&quot;#CC0000&quot;&gt;HTTP&lt;/font&gt;" style="text;html=1;resizable=0;points=[];autosize=1;align=left;verticalAlign=top;spacingTop=-4;rounded=1;" parent="1" vertex="1">
<mxGeometry x="57.5" y="1000" width="50" height="20" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-15" value="Interface or Connection Type" style="text;html=1;resizable=0;points=[];autosize=1;align=left;verticalAlign=top;spacingTop=-4;rounded=1;" parent="1" vertex="1">
<mxGeometry x="128" y="1000" width="200" height="20" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-17" value="GOOGLE MAP" style="ellipse;shape=cloud;whiteSpace=wrap;html=1;align=center;rounded=1;" parent="1" vertex="1">
<mxGeometry x="50" y="620" width="160" height="100" as="geometry"/>
</mxCell>
<mxCell id="q6xpdlAktihQ9t4JN2tA-18" value="" style="endArrow=classic;startArrow=classic;html=1;exitX=0.88;exitY=0.25;exitDx=0;exitDy=0;exitPerimeter=0;entryX=0;entryY=0.75;entryDx=0;entryDy=0;strokeColor=#000000;" parent="1" source="q6xpdlAktihQ9t4JN2tA-17" target="ChM7FxRyLafK2Ug-lwnD-3" edge="1">
<mxGeometry width="50" height="50" relative="1" as="geometry">
<mxPoint x="220" y="650" as="sourcePoint"/>
<mxPoint x="380" y="640" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="28" value="&lt;font color=&quot;#ff0000&quot;&gt;HTTP&lt;br&gt;&lt;/font&gt;- Map" style="edgeLabel;html=1;align=center;verticalAlign=middle;resizable=0;points=[];fontColor=#FFFFFF;" parent="q6xpdlAktihQ9t4JN2tA-18" vertex="1" connectable="0">
<mxGeometry x="0.0965" y="1" relative="1" as="geometry">
<mxPoint as="offset"/>
</mxGeometry>
</mxCell>
<mxCell id="11" value="&lt;font color=&quot;#ff0000&quot;&gt;TCP&lt;/font&gt;&lt;br&gt;&lt;font color=&quot;#ffffff&quot;&gt;- Raw Text&lt;/font&gt;" style="edgeStyle=none;orthogonalLoop=1;jettySize=auto;html=1;exitX=0.5;exitY=0;exitDx=0;exitDy=0;entryX=0.5;entryY=1;entryDx=0;entryDy=0;startArrow=classic;startFill=1;endArrow=none;endFill=0;strokeColor=#000000;" parent="1" source="3" target="7" edge="1">
<mxGeometry relative="1" as="geometry"/>
</mxCell>
<mxCell id="3" value="&lt;div&gt;&lt;font color=&quot;#3333ff&quot;&gt;fldigi Bridge&lt;/font&gt;&lt;/div&gt;" style="whiteSpace=wrap;html=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="115" y="170" width="110" height="40" as="geometry"/>
</mxCell>
<mxCell id="7" value="&lt;div&gt;&lt;font color=&quot;#ffffff&quot;&gt;fldigi&lt;/font&gt;&lt;/div&gt;" style="whiteSpace=wrap;html=1;rounded=1;" parent="1" vertex="1">
<mxGeometry x="115" y="80" width="110" height="40" as="geometry"/>
</mxCell>
<mxCell id="13" value="&lt;b&gt;ABANDONED&lt;/b&gt;" style="text;html=1;strokeColor=none;fillColor=none;align=center;verticalAlign=middle;whiteSpace=wrap;shadow=0;glass=0;sketch=0;fontColor=#FF0000;opacity=50;rounded=1;" parent="1" vertex="1">
<mxGeometry x="630" y="130" width="40" height="20" as="geometry"/>
</mxCell>
<mxCell id="27" value="&lt;font color=&quot;#ff0000&quot;&gt;USB - Serial&lt;/font&gt;" style="rounded=0;orthogonalLoop=1;jettySize=auto;html=1;exitX=0;exitY=0;exitDx=0;exitDy=20;exitPerimeter=0;entryX=1;entryY=0.25;entryDx=0;entryDy=0;fontColor=#FFFFFF;strokeColor=#000000;" parent="1" edge="1">
<mxGeometry relative="1" as="geometry">
<mxPoint x="321" y="380" as="sourcePoint"/>
<mxPoint x="211" y="415" as="targetPoint"/>
</mxGeometry>
</mxCell>
<mxCell id="14" value="GPS Receiver" style="shape=cube;whiteSpace=wrap;html=1;boundedLbl=1;backgroundOutline=1;darkOpacity=0.05;darkOpacity2=0.1;fillColor=#2a2a2a;gradientColor=none;fontColor=#f0f0f0;align=center;rounded=1;" parent="1" vertex="1">
<mxGeometry x="320" y="360" width="100" height="60" as="geometry"/>
</mxCell>
</root>
</mxGraphModel>
</diagram>
</mxfile>

Plik binarny nie jest wyświetlany.

Po

Szerokość:  |  Wysokość:  |  Rozmiar: 113 KiB

73
docs/misc.md 100644
Wyświetl plik

@ -0,0 +1,73 @@
### BROWSER SETTINGS for relaxed HTTPS
#### FIREFOX:
about:config -->
- security.mixed_content.block_active_content = false
- network.websocket.allowInsecureFromHTTPS = true <<< this should be enough for habdec websocket
network.stricttransportsecurity.preloadlist = false
#### CHROME:
chrome://flags -->
- Insecure origins treated as secure
### SSL cert generate - for data server
openssl req -new -x509 -days 1095 -nodes -newkey rsa:2048 -out cacert.pem -keyout privkey.pem -subj "/CN=192.168.100.53"
### UBUNTU SERVER CONFIG
### disable firewall: ```sudo ufw disable```
### apache ssl:
```
su -
a2enmod ssl
systemctl restart apache2
openssl genrsa -out ca.key 2048
openssl req -nodes -new -key ca.key -out ca.csr
openssl x509 -req -days 365 -in ca.csr -signkey ca.key -out ca.crt
mkdir /etc/apache2/ssl/
cp ca.crt ca.key ca.csr /etc/apache2/ssl/
```
```
nano /etc/apache2/sites-enable/000-default.conf
"Comment out all the lines by adding a “#” in front of each line and add the following lines:"
<VirtualHost *:443>
ServerAdmin webmaster@localhost
DocumentRoot /var/www/html
ErrorLog ${APACHE_LOG_DIR}/error.log
CustomLog ${APACHE_LOG_DIR}/access.log combined
SSLEngine on
SSLCertificateFile /etc/apache2/ssl/ca.crt
SSLCertificateKeyFile /etc/apache2/ssl/ca.key
</VirtualHost>
systemctl restart apache2
```
### Disable Unattended Upgrade in Ubuntu 16.04
https://askubuntu.com/questions/953779/programmatically-disable-apt-unattended-upgrades
```
sudo nano /etc/apt/apt.conf.d/10periodic
APT::Periodic::Update-Package-Lists "0";
APT::Periodic::Unattended-Upgrade "0";
```
```
sudo nano /etc/apt/apt.conf.d/20auto-upgrades
APT::Periodic::Update-Package-Lists "0";
APT::Periodic::Unattended-Upgrade "0";
```
```
sudo cp /usr/share/unattended-upgrades/20auto-upgrades-disabled /etc/apt/apt.conf.d/
```

Wyświetl plik

@ -0,0 +1,5 @@
An interface between hardware and other HABBOY components.
Specifically a websocket interface for browser GUI.
It gathers GPS, joystick and buttons signals and provides them through different interfaces, ie: websocket, UDP, REST-like http
Currently this is very outdated.

Wyświetl plik

@ -0,0 +1,170 @@
# https://github.com/rpavlik/cmake-modules
# - Returns a version string from Git
#
# These functions force a re-configure on each git commit so that you can
# trust the values of the variables in your build system.
#
# get_git_head_revision(<refspecvar> <hashvar> [<additional arguments to git describe> ...])
#
# Returns the refspec and sha hash of the current head revision
#
# git_describe(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe on the source tree, and adjusting
# the output so that it tests false if an error occurs.
#
# git_get_exact_tag(<var> [<additional arguments to git describe> ...])
#
# Returns the results of git describe --exact-match on the source tree,
# and adjusting the output so that it tests false if there was no exact
# matching tag.
#
# git_local_changes(<var>)
#
# Returns either "CLEAN" or "DIRTY" with respect to uncommitted changes.
# Uses the return code of "git diff-index --quiet HEAD --".
# Does not regard untracked files.
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net>
# http://academic.cleardefinition.com
# Iowa State University HCI Graduate Program/VRAC
#
# Copyright Iowa State University 2009-2010.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
if(__get_git_revision_description)
return()
endif()
set(__get_git_revision_description YES)
# We must run the following at "include" time, not at function call time,
# to find the path to this module rather than the path to a calling list file
get_filename_component(_gitdescmoddir ${CMAKE_CURRENT_LIST_FILE} PATH)
function(get_git_head_revision _refspecvar _hashvar)
set(GIT_PARENT_DIR "${CMAKE_CURRENT_SOURCE_DIR}")
set(GIT_DIR "${GIT_PARENT_DIR}/.git")
while(NOT EXISTS "${GIT_DIR}") # .git dir not found, search parent directories
set(GIT_PREVIOUS_PARENT "${GIT_PARENT_DIR}")
get_filename_component(GIT_PARENT_DIR ${GIT_PARENT_DIR} PATH)
if(GIT_PARENT_DIR STREQUAL GIT_PREVIOUS_PARENT)
# We have reached the root directory, we are not in git
set(${_refspecvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
set(${_hashvar} "GITDIR-NOTFOUND" PARENT_SCOPE)
return()
endif()
set(GIT_DIR "${GIT_PARENT_DIR}/.git")
endwhile()
# check if this is a submodule
if(NOT IS_DIRECTORY ${GIT_DIR})
file(READ ${GIT_DIR} submodule)
string(REGEX REPLACE "gitdir: (.*)\n$" "\\1" GIT_DIR_RELATIVE ${submodule})
get_filename_component(SUBMODULE_DIR ${GIT_DIR} PATH)
get_filename_component(GIT_DIR ${SUBMODULE_DIR}/${GIT_DIR_RELATIVE} ABSOLUTE)
endif()
set(GIT_DATA "${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/git-data")
if(NOT EXISTS "${GIT_DATA}")
file(MAKE_DIRECTORY "${GIT_DATA}")
endif()
if(NOT EXISTS "${GIT_DIR}/HEAD")
return()
endif()
set(HEAD_FILE "${GIT_DATA}/HEAD")
configure_file("${GIT_DIR}/HEAD" "${HEAD_FILE}" COPYONLY)
configure_file("${_gitdescmoddir}/GetGitRevisionDescription.cmake.in"
"${GIT_DATA}/grabRef.cmake"
@ONLY)
include("${GIT_DATA}/grabRef.cmake")
set(${_refspecvar} "${HEAD_REF}" PARENT_SCOPE)
set(${_hashvar} "${HEAD_HASH}" PARENT_SCOPE)
endfunction()
function(git_describe _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
return()
endif()
# TODO sanitize
#if((${ARGN}" MATCHES "&&") OR
# (ARGN MATCHES "||") OR
# (ARGN MATCHES "\\;"))
# message("Please report the following error to the project!")
# message(FATAL_ERROR "Looks like someone's doing something nefarious with git_describe! Passed arguments ${ARGN}")
#endif()
#message(STATUS "Arguments to execute_process: ${ARGN}")
execute_process(COMMAND
"${GIT_EXECUTABLE}"
describe
${hash}
${ARGN}
WORKING_DIRECTORY
"${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE
res
OUTPUT_VARIABLE
out
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(NOT res EQUAL 0)
set(out "${out}-${res}-NOTFOUND")
endif()
set(${_var} "${out}" PARENT_SCOPE)
endfunction()
function(git_get_exact_tag _var)
git_describe(out --exact-match ${ARGN})
set(${_var} "${out}" PARENT_SCOPE)
endfunction()
function(git_local_changes _var)
if(NOT GIT_FOUND)
find_package(Git QUIET)
endif()
get_git_head_revision(refspec hash)
if(NOT GIT_FOUND)
set(${_var} "GIT-NOTFOUND" PARENT_SCOPE)
return()
endif()
if(NOT hash)
set(${_var} "HEAD-HASH-NOTFOUND" PARENT_SCOPE)
return()
endif()
execute_process(COMMAND
"${GIT_EXECUTABLE}"
diff-index --quiet HEAD --
WORKING_DIRECTORY
"${CMAKE_CURRENT_SOURCE_DIR}"
RESULT_VARIABLE
res
OUTPUT_VARIABLE
out
ERROR_QUIET
OUTPUT_STRIP_TRAILING_WHITESPACE)
if(res EQUAL 0)
set(${_var} "CLEAN" PARENT_SCOPE)
else()
set(${_var} "DIRTY" PARENT_SCOPE)
endif()
endfunction()

Wyświetl plik

@ -0,0 +1,43 @@
# https://github.com/rpavlik/cmake-modules
#
# Internal file for GetGitRevisionDescription.cmake
#
# Requires CMake 2.6 or newer (uses the 'function' command)
#
# Original Author:
# 2009-2010 Ryan Pavlik <rpavlik@iastate.edu> <abiryan@ryand.net>
# http://academic.cleardefinition.com
# Iowa State University HCI Graduate Program/VRAC
#
# Copyright Iowa State University 2009-2010.
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
set(HEAD_HASH)
file(READ "@HEAD_FILE@" HEAD_CONTENTS LIMIT 1024)
string(STRIP "${HEAD_CONTENTS}" HEAD_CONTENTS)
if(HEAD_CONTENTS MATCHES "ref")
# named branch
string(REPLACE "ref: " "" HEAD_REF "${HEAD_CONTENTS}")
if(EXISTS "@GIT_DIR@/${HEAD_REF}")
configure_file("@GIT_DIR@/${HEAD_REF}" "@GIT_DATA@/head-ref" COPYONLY)
else()
configure_file("@GIT_DIR@/packed-refs" "@GIT_DATA@/packed-refs" COPYONLY)
file(READ "@GIT_DATA@/packed-refs" PACKED_REFS)
if(${PACKED_REFS} MATCHES "([0-9a-z]*) ${HEAD_REF}")
set(HEAD_HASH "${CMAKE_MATCH_1}")
endif()
endif()
else()
# detached HEAD
configure_file("@GIT_DIR@/HEAD" "@GIT_DATA@/head-ref" COPYONLY)
endif()
if(NOT HEAD_HASH)
file(READ "@GIT_DATA@/head-ref" HEAD_HASH LIMIT 1024)
string(STRIP "${HEAD_HASH}" HEAD_HASH)
endif()

Wyświetl plik

@ -0,0 +1,86 @@
cmake_minimum_required( VERSION 3.8.2 )
project (habboy_hw_iface)
set ( CMAKE_CXX_STANDARD 17 )
# set ( CMAKE_BUILD_TYPE "Debug" )
# set ( CMAKE_BUILD_TYPE "Release" )
if(NOT CMAKE_BUILD_TYPE)
set(CMAKE_BUILD_TYPE "Release")
endif()
if ( CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT )
set ( CMAKE_INSTALL_PREFIX "${CMAKE_BINARY_DIR}/install" CACHE PATH "Install dir" FORCE)
endif()
message ( "CMAKE_INSTALL_PREFIX: " ${CMAKE_INSTALL_PREFIX} )
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/CMake/")
include(GetGitRevisionDescription)
get_git_head_revision(GIT_REFSPEC GIT_SHA1)
include_directories( ${PROJECT_SOURCE_DIR} )
include_directories( ${CMAKE_CURRENT_SOURCE_DIR} )
# boost
set ( Boost_NO_BOOST_CMAKE ON )
set ( Boost_NO_SYSTEM_PATHS ON )
set ( Boost_USE_STATIC_LIBS ON )
add_definitions ( -DBOOST_ALL_NO_LIB )
find_package(Boost REQUIRED COMPONENTS program_options system date_time )
include_directories( ${Boost_INCLUDE_DIRS} )
message ( "Boost_INCLUDE_DIRS " ${Boost_INCLUDE_DIRS} )
message ( "Boost_LIBRARY_DIRS " ${Boost_LIBRARY_DIRS} )
set( CMAKE_CXX_FLAGS " -O3 " )
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
# set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wshadow" )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-class-memaccess" )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable" )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter" )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Werror=return-type" )
elseif ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
SET(CMAKE_CXX_FLAGS "/EHsc")
add_definitions( -D_USE_MATH_DEFINES )
endif()
set (PlatformSpecificLinking "")
if ("${CMAKE_CXX_COMPILER_ID}" STREQUAL "GNU")
set (PlatformSpecificLinking "pthread")
endif()
set ( habboy_hw_iface_src
console_colors.h console_colors.cpp
pystring.h pystring.cpp
program_options.h program_options.cpp
GpsState.h GpsState.cpp
ws_server.h ws_server.cpp
hb_serial.h hb_serial.cpp
listener.h listener.cpp
http_session.h http_session.cpp
websocket_session.h websocket_session.cpp
msg_broker.h msg_broker.cpp
main.cpp
)
# compile in git repo version
configure_file("${PROJECT_SOURCE_DIR}/git_repo_sha1.cpp.in" "${CMAKE_CURRENT_BINARY_DIR}/git_repo_sha1.cpp" @ONLY)
list(APPEND habboy_hw_iface_src "${CMAKE_CURRENT_BINARY_DIR}/git_repo_sha1.cpp" ${PROJECT_SOURCE_DIR}/git_repo_sha1.h)
add_executable ( habboy_hw_iface ${habboy_hw_iface_src} )
target_link_libraries( habboy_hw_iface
${Boost_LIBRARIES}
${PlatformSpecificLinking} )
install ( TARGETS habboy_hw_iface DESTINATION ${CMAKE_INSTALL_PREFIX} )
install ( FILES ${PROJECT_SOURCE_DIR}/habLogger/habLogger.py
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
DESTINATION ${CMAKE_INSTALL_PREFIX} )
file( WRITE ${CMAKE_CURRENT_BINARY_DIR}/run_loop.sh "#!/bin/sh\n while true; do ./habboy_hw_iface --config ./habdechabboy_hw_iface.opts; done\n" )
install ( FILES ${CMAKE_CURRENT_BINARY_DIR}/run_loop.sh
PERMISSIONS OWNER_EXECUTE OWNER_WRITE OWNER_READ
DESTINATION ${CMAKE_INSTALL_PREFIX} )

Wyświetl plik

@ -0,0 +1,69 @@
#pragma once
#include <string>
#include <iomanip>
#include <fstream>
#include <vector>
#include <mutex>
#include <unordered_set>
#include "websocket_session.h"
#include "GpsState.h"
#include "hb_serial.h"
// singleton class keeping all global data
class GLOBALS
{
public:
GLOBALS(GLOBALS const&) = delete;
void operator=(GLOBALS const&) = delete;
static GLOBALS& get()
{
static GLOBALS instance_;
return instance_;
}
// CLI parameters
struct PARAMS
{
std::string ws_host_ = "0.0.0.0"; //websocket
int ws_port_ = 5565; //websocket
std::string serial_ = "/dev/ttySAC0"; // serial port to arduino
habboy_hw_iface::SerialConnection::Baud baud_ = habboy_hw_iface::SerialConnection::Baud::b9600;
};
PARAMS par_;
// state
habboy_hw_iface::GpsState gps_;
static bool DumpToFile(std::string fName)
{
using namespace std;
try{
fstream oFile(fName, fstream::out);
oFile<<"port = "<<GLOBALS::get().par_.ws_host_<<":"<<GLOBALS::get().par_.ws_port_<<endl;
oFile<<"serial = "<<GLOBALS::get().par_.serial_<<endl;
}
catch (exception& e) {
cout<<"Can't save config "<<fName<<endl;
return false;
}
return true;
}
static void Print()
{
using namespace std;
cout<<"\tws_host: "<<GLOBALS::get().par_.ws_host_<<endl;
cout<<"\tws_port: "<<GLOBALS::get().par_.ws_port_<<endl;
cout<<"\tserial: "<<GLOBALS::get().par_.serial_<<endl;
cout<<"\tbaud: "<<GLOBALS::get().par_.baud_<<endl;
}
private:
GLOBALS() {};
};

Wyświetl plik

@ -0,0 +1,50 @@
#include "GpsState.h"
#include <iostream>
#include <vector>
#include "pystring.h"
namespace habboy_hw_iface
{
std::string GpsState::to_str() const
{
using namespace std;
string res;
res += "time=" + to_string(time) + ",";
res += "lat=" + to_string(lat) + ",";
res += "lon=" + to_string(lon) + ",";
res += "alt=" + to_string(alt) + ",";
res += "altmsl=" + to_string(altmsl) + ",";
res += "sats=" + to_string(sats) + ",";
res += "speed=" + to_string(speed) + ",";
res += "heading=" + to_string(heading);
return res;
}
void GpsState::from_str(std::string str)
{
using namespace std;
vector<string> tokens;
pystring::split( str, tokens, "," );
for(auto t : tokens)
{
vector<string> kv;
pystring::split( t, kv, "=" );
if(kv.size() == 2)
{
if( kv[0] == "time" ) try { time = stoi(kv[1]); } catch(exception& e) { cout<<"ERR "<<e.what()<<". "<<kv[0]<<" "<<kv[1]<<endl; }
if( kv[0] == "lat" ) try { lat = stof(kv[1]); } catch(exception& e) { cout<<"ERR "<<e.what()<<". "<<kv[0]<<" "<<kv[1]<<endl; }
if( kv[0] == "lon" ) try { lon = stof(kv[1]); } catch(exception& e) { cout<<"ERR "<<e.what()<<". "<<kv[0]<<" "<<kv[1]<<endl; }
if( kv[0] == "alt" ) try { alt = stof(kv[1]); } catch(exception& e) { cout<<"ERR "<<e.what()<<". "<<kv[0]<<" "<<kv[1]<<endl; }
if( kv[0] == "altmsl" ) try { altmsl = stof(kv[1]); } catch(exception& e) { cout<<"ERR "<<e.what()<<". "<<kv[0]<<" "<<kv[1]<<endl; }
if( kv[0] == "sats" ) try { sats = stoi(kv[1]); } catch(exception& e) { cout<<"ERR "<<e.what()<<". "<<kv[0]<<" "<<kv[1]<<endl; }
if( kv[0] == "speed" ) try { speed = stof(kv[1]); } catch(exception& e) { cout<<"ERR "<<e.what()<<". "<<kv[0]<<" "<<kv[1]<<endl; }
if( kv[0] == "heading" ) try { heading = stof(kv[1]); } catch(exception& e) { cout<<"ERR "<<e.what()<<". "<<kv[0]<<" "<<kv[1]<<endl; }
}
}
}
} //ns

Wyświetl plik

@ -0,0 +1,24 @@
#pragma once
#include <string>
namespace habboy_hw_iface
{
class GpsState
{
public:
int time = 0;
float lat = 0;
float lon = 0;
float alt = 0;
float altmsl = 0;
int sats = -1;
float speed = 0;
float heading = 0;
std::string to_str() const;
void from_str(std::string str);
};
} //ns

Wyświetl plik

@ -0,0 +1,28 @@
#ifdef __linux__
const char* C_BLACK = "\033[1;30m";
const char* C_RED = "\033[1;31m";
const char* C_GREEN = "\033[1;32m";
const char* C_BROWN = "\033[1;33m";
const char* C_BLUE = "\033[1;34m";
const char* C_MAGENTA = "\033[1;35m";
const char* C_CYAN = "\033[1;36m";
const char* C_LIGHTGREY = "\033[1;37m";
const char* C_OFF = "\033[0m";
const char* C_CLEAR = "\033[2K";
// #elif _WIN32
// #elif __APPLE__
// #elif __unix__ // all unices not caught above
// #elif defined(_POSIX_VERSION)
#else
const char* C_BLACK = "";
const char* C_RED = "";
const char* C_GREEN = "";
const char* C_BROWN = "";
const char* C_BLUE = "";
const char* C_MAGENTA = "";
const char* C_CYAN = "";
const char* C_LIGHTGREY = "";
const char* C_OFF = "";
const char* C_CLEAR = "";
#endif

Wyświetl plik

@ -0,0 +1,12 @@
#pragma once
extern const char* C_BLACK;
extern const char* C_RED;
extern const char* C_GREEN;
extern const char* C_BROWN;
extern const char* C_BLUE;
extern const char* C_MAGENTA;
extern const char* C_CYAN;
extern const char* C_LIGHTGREY;
extern const char* C_OFF;
extern const char* C_CLEAR;

Wyświetl plik

@ -0,0 +1,2 @@
#define GIT_SHA1 "@GIT_SHA1@"
char g_GIT_SHA1[] = GIT_SHA1;

Wyświetl plik

@ -0,0 +1 @@
extern char g_GIT_SHA1[];

Wyświetl plik

@ -0,0 +1,191 @@
#include <hb_serial.h>
#include <thread>
#include <chrono>
#include <string>
#include <iostream>
// serial
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>
namespace
{
void error_message(const char* err_m, int _errno, ...)
{
printf(err_m);
// printf("\n");
}
int set_interface_attribs(int fd, int speed, int parity)
{
struct termios tty;
memset(&tty, 0, sizeof tty);
if (tcgetattr(fd, &tty) != 0)
{
error_message("error %d from tcgetattr", errno);
return -1;
}
cfsetospeed(&tty, speed);
cfsetispeed(&tty, speed);
tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8; // 8-bit chars
// disable IGNBRK for mismatched speed tests; otherwise receive break
// as \000 chars
tty.c_iflag &= ~IGNBRK; // disable break processing
tty.c_lflag = 0; // no signaling chars, no echo,
// no canonical processing
tty.c_oflag = 0; // no remapping, no delays
tty.c_cc[VMIN] = 0; // read doesn't block
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl
tty.c_cflag |= (CLOCAL | CREAD); // ignore modem controls,
// enable reading
tty.c_cflag &= ~(PARENB | PARODD); // shut off parity
tty.c_cflag |= parity;
tty.c_cflag &= ~CSTOPB;
tty.c_cflag &= ~CRTSCTS;
if (tcsetattr(fd, TCSANOW, &tty) != 0)
{
error_message("error %d from tcsetattr", errno);
return -1;
}
return 0;
}
void set_blocking(int fd, int should_block)
{
struct termios tty;
memset(&tty, 0, sizeof tty);
if (tcgetattr(fd, &tty) != 0)
{
error_message("error %d from tggetattr", errno);
return;
}
tty.c_cc[VMIN] = should_block ? 1 : 0;
tty.c_cc[VTIME] = 5; // 0.5 seconds read timeout
if (tcsetattr(fd, TCSANOW, &tty) != 0)
error_message("error %d setting term attributes", errno);
}
} //ns
namespace habboy_hw_iface
{
void SerialConnection::add_callback(callback_type cb)
{
callbacks_.push_back(cb);
}
void SerialConnection::operator()()
{
using namespace std;
int fd = open(port_.c_str(), O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
cerr<<("error opening serial port. ", errno, port_, strerror(errno));
return;
}
set_interface_attribs(fd, baud_, 0); // set speed to 115,200 bps, 8n1 (no parity)
set_blocking(fd, 0); // set no blocking
// write(fd, "hello!\n", 7); // send 7 character greeting
char buf[100];
string buf_str;
while(keep_running_)
{
// usleep((7 + 25) * 100); // sleep enough to transmit the 7 plus
// receive 25: approx 100 uS per char transmit
usleep(1 * 100000); // sleep enough to transmit the 7 plus
int n = read(fd, buf, sizeof buf); // read up to 100 characters if ready to read
string part(buf, n);
buf_str += part;
auto _end = buf_str.find("\n");
if(_end != std::string::npos)
{
string msg = buf_str.substr(0, _end);
std::cout<<"SERIAL : "<<msg<<std::endl;
buf_str = buf_str.substr(_end+1);
for(auto cb : callbacks_)
cb(msg);
}
}
}
// needed for boost::program_options
std::istream& operator>>(std::istream& in, SerialConnection::Baud& b)
{
std::string token;
in >> token;
if (token == "0") b = SerialConnection::Baud::b0;
else if (token == "1") b = SerialConnection::Baud::b50;
else if (token == "2") b = SerialConnection::Baud::b75;
else if (token == "3") b = SerialConnection::Baud::b110;
else if (token == "4") b = SerialConnection::Baud::b134;
else if (token == "5") b = SerialConnection::Baud::b150;
else if (token == "6") b = SerialConnection::Baud::b200;
else if (token == "7") b = SerialConnection::Baud::b300;
else if (token == "8") b = SerialConnection::Baud::b600;
else if (token == "9") b = SerialConnection::Baud::b1200;
else if (token == "10") b = SerialConnection::Baud::b1800;
else if (token == "10") b = SerialConnection::Baud::b2400;
else if (token == "12") b = SerialConnection::Baud::b4800;
else if (token == "13") b = SerialConnection::Baud::b9600;
else if (token == "14") b = SerialConnection::Baud::b19200;
else if (token == "15") b = SerialConnection::Baud::b38400;
else if (token == "16") b = SerialConnection::Baud::b57600;
else if (token == "17") b = SerialConnection::Baud::b115200;
else if (token == "18") b = SerialConnection::Baud::b230400;
return in;
}
std::ostream& operator<<(std::ostream& os, const SerialConnection::Baud& b)
{
if (b == SerialConnection::Baud::b0) os<<"B0";
else if (b == SerialConnection::Baud::b50) os<<"B50";
else if (b == SerialConnection::Baud::b75) os<<"B75";
else if (b == SerialConnection::Baud::b110) os<<"B110";
else if (b == SerialConnection::Baud::b134) os<<"B134";
else if (b == SerialConnection::Baud::b150) os<<"B150";
else if (b == SerialConnection::Baud::b200) os<<"B200";
else if (b == SerialConnection::Baud::b300) os<<"B300";
else if (b == SerialConnection::Baud::b600) os<<"B600";
else if (b == SerialConnection::Baud::b1200) os<<"B1200";
else if (b == SerialConnection::Baud::b1800) os<<"B1800";
else if (b == SerialConnection::Baud::b2400) os<<"B2400";
else if (b == SerialConnection::Baud::b4800) os<<"B4800";
else if (b == SerialConnection::Baud::b9600) os<<"B9600";
else if (b == SerialConnection::Baud::b19200) os<<"B19200";
else if (b == SerialConnection::Baud::b38400) os<<"B38400";
else if (b == SerialConnection::Baud::b57600) os<<"B57600";
else if (b == SerialConnection::Baud::b115200) os<<"B115200";
else if (b == SerialConnection::Baud::b230400) os<<"B230400";
return os;
}
} //ns habboy_hw_iface

Wyświetl plik

@ -0,0 +1,64 @@
#pragma once
#include <string>
#include <vector>
#include <functional>
#include <termios.h>
namespace habboy_hw_iface
{
// void RunSerialConnection( std::function<void(const std::string&)> msg_callback);
class SerialConnection
{
public:
typedef std::function<void (const std::string&)> callback_type;
enum Baud {
b0 = B0,
b50 = B50,
b75 = B75,
b110 = B110,
b134 = B134,
b150 = B150,
b200 = B200,
b300 = B300,
b600 = B600,
b1200 = B1200,
b1800 = B1800,
b2400 = B2400,
b4800 = B4800,
b9600 = B9600,
b19200 = B19200,
b38400 = B38400,
b57600 = B57600,
b115200 = B115200,
b230400 = B230400
};
SerialConnection() = delete;
SerialConnection(const SerialConnection&) = delete;
SerialConnection& operator=(const SerialConnection&) = delete;
SerialConnection(std::string port, Baud baud) : port_(port), baud_(baud) {};
void add_callback(callback_type);
void operator()();
void Stop() {keep_running_ = false;}
private:
std::string port_{""};
// unsigned int baud_{0};
Baud baud_{Baud::b115200};
std::vector<callback_type> callbacks_;
bool keep_running_ = true;
};
// needed for boost::program_options
std::istream& operator>>(std::istream& in, SerialConnection::Baud& b);
std::ostream& operator<<(std::ostream& os, const SerialConnection::Baud& b);
}

Wyświetl plik

@ -0,0 +1,277 @@
#include "http_session.h"
#include "websocket_session.h"
#include <iostream>
//------------------------------------------------------------------------------
// Return a reasonable mime type based on the extension of a file.
/*
boost::beast::string_view
mime_type(boost::beast::string_view path)
{
using boost::beast::iequals;
auto const ext = [&path]
{
auto const pos = path.rfind(".");
if(pos == boost::beast::string_view::npos)
return boost::beast::string_view{};
return path.substr(pos);
}();
if(iequals(ext, ".htm")) return "text/html";
if(iequals(ext, ".html")) return "text/html";
if(iequals(ext, ".php")) return "text/html";
if(iequals(ext, ".css")) return "text/css";
if(iequals(ext, ".txt")) return "text/plain";
if(iequals(ext, ".js")) return "application/javascript";
if(iequals(ext, ".json")) return "application/json";
if(iequals(ext, ".xml")) return "application/xml";
if(iequals(ext, ".swf")) return "application/x-shockwave-flash";
if(iequals(ext, ".flv")) return "video/x-flv";
if(iequals(ext, ".png")) return "image/png";
if(iequals(ext, ".jpe")) return "image/jpeg";
if(iequals(ext, ".jpeg")) return "image/jpeg";
if(iequals(ext, ".jpg")) return "image/jpeg";
if(iequals(ext, ".gif")) return "image/gif";
if(iequals(ext, ".bmp")) return "image/bmp";
if(iequals(ext, ".ico")) return "image/vnd.microsoft.icon";
if(iequals(ext, ".tiff")) return "image/tiff";
if(iequals(ext, ".tif")) return "image/tiff";
if(iequals(ext, ".svg")) return "image/svg+xml";
if(iequals(ext, ".svgz")) return "image/svg+xml";
return "application/text";
}
*/
// Append an HTTP rel-path to a local filesystem path.
// The returned path is normalized for the platform.
/*
std::string
path_cat(
boost::beast::string_view base,
boost::beast::string_view path)
{
if(base.empty())
return path.to_string();
std::string result = base.to_string();
#if BOOST_MSVC
char constexpr path_separator = '\\';
if(result.back() == path_separator)
result.resize(result.size() - 1);
result.append(path.data(), path.size());
for(auto& c : result)
if(c == '/')
c = path_separator;
#else
char constexpr path_separator = '/';
if(result.back() == path_separator)
result.resize(result.size() - 1);
result.append(path.data(), path.size());
#endif
return result;
}
*/
// This function produces an HTTP response for the given
// request. The type of the response object depends on the
// contents of the request, so the interface requires the
// caller to pass a generic lambda for receiving the response.
/*
template<
class Body, class Allocator,
class Send>
void
handle_request(
boost::beast::string_view doc_root,
http::request<Body, http::basic_fields<Allocator>>&& req,
Send&& send)
{
// Returns a bad request response
auto const bad_request =
[&req](boost::beast::string_view why)
{
http::response<http::string_body> res{http::status::bad_request, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = why.to_string();
res.prepare_payload();
return res;
};
// Returns a not found response
auto const not_found =
[&req](boost::beast::string_view target)
{
http::response<http::string_body> res{http::status::not_found, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = "The resource '" + target.to_string() + "' was not found.";
res.prepare_payload();
return res;
};
// Returns a server error response
auto const server_error =
[&req](boost::beast::string_view what)
{
http::response<http::string_body> res{http::status::internal_server_error, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, "text/html");
res.keep_alive(req.keep_alive());
res.body() = "An error occurred: '" + what.to_string() + "'";
res.prepare_payload();
return res;
};
// Make sure we can handle the method
if( req.method() != http::verb::get &&
req.method() != http::verb::head)
return send(bad_request("Unknown HTTP-method"));
// Request path must be absolute and not contain "..".
if( req.target().empty() ||
req.target()[0] != '/' ||
req.target().find("..") != boost::beast::string_view::npos)
return send(bad_request("Illegal request-target"));
// Build the path to the requested file
std::string path = path_cat(doc_root, req.target());
if(req.target().back() == '/')
path.append("index.html");
// Attempt to open the file
boost::beast::error_code ec;
http::file_body::value_type body;
body.open(path.c_str(), boost::beast::file_mode::scan, ec);
// Handle the case where the file doesn't exist
if(ec == boost::system::errc::no_such_file_or_directory)
return send(not_found(req.target()));
// Handle an unknown error
if(ec)
return send(server_error(ec.message()));
// Cache the size since we need it after the move
auto const size = body.size();
// Respond to HEAD request
if(req.method() == http::verb::head)
{
http::response<http::empty_body> res{http::status::ok, req.version()};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, mime_type(path));
res.content_length(size);
res.keep_alive(req.keep_alive());
return send(std::move(res));
}
// Respond to GET request
http::response<http::file_body> res{
std::piecewise_construct,
std::make_tuple(std::move(body)),
std::make_tuple(http::status::ok, req.version())};
res.set(http::field::server, BOOST_BEAST_VERSION_STRING);
res.set(http::field::content_type, mime_type(path));
res.content_length(size);
res.keep_alive(req.keep_alive());
return send(std::move(res));
}
*/
//------------------------------------------------------------------------------
namespace habboy_hw_iface
{
http_session::http_session(
tcp::socket socket,
std::shared_ptr<habboy_hw_iface::WebsocketServer> p_ws_server)
: socket_(std::move(socket)),
p_ws_server_(p_ws_server)
{
}
void http_session::run()
{
boost::beast::http::async_read(socket_, buffer_, req_,
[self = shared_from_this()]
(error_code ec, std::size_t bytes)
{
self->on_read(ec, bytes);
});
}
void http_session::fail(error_code ec, char const* what)
{
if(ec == net::error::operation_aborted)
return;
std::cerr << what << ": " << ec.message() << "\n";
}
void http_session::on_read(error_code ec, std::size_t)
{
if(ec == boost::beast::http::error::end_of_stream)
{
socket_.shutdown(tcp::socket::shutdown_send, ec);
return;
}
if(ec)
return fail(ec, "read");
if(boost::beast::websocket::is_upgrade(req_))
{
std::make_shared<websocket_session>(
std::move(socket_), p_ws_server_
)->run(std::move(req_));
return;
}
// Send the response
/*
handle_request(state_->doc_root(), std::move(req_),
[this](auto&& response)
{
// The lifetime of the message has to extend
// for the duration of the async operation so
// we use a shared_ptr to manage it.
using response_type = typename std::decay<decltype(response)>::type;
auto sp = std::make_shared<response_type>(std::forward<decltype(response)>(response));
// Write the response
auto self = shared_from_this();
http::async_write(this->socket_, *sp,
[self, sp](
error_code ec, std::size_t bytes)
{
self->on_write(ec, bytes, sp->need_eof());
});
});
*/
}
void http_session::on_write(error_code ec, std::size_t, bool close)
{
if(ec)
return fail(ec, "write");
if(close)
{
socket_.shutdown(tcp::socket::shutdown_send, ec);
return;
}
// Clear contents of the request message,
// otherwise the read behavior is undefined.
req_ = {};
boost::beast::http::async_read(socket_, buffer_, req_,
[self = shared_from_this()]
(error_code ec, std::size_t bytes)
{
self->on_read(ec, bytes);
});
}
} //ns

Wyświetl plik

@ -0,0 +1,35 @@
#pragma once
#include <cstdlib>
#include <memory>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include "ws_server.h"
namespace net = boost::asio; // namespace asio
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
using error_code = boost::system::error_code; // from <boost/system/error_code.hpp>
namespace habboy_hw_iface
{
class http_session : public std::enable_shared_from_this<http_session>
{
tcp::socket socket_;
boost::beast::flat_buffer buffer_;
boost::beast::http::request<boost::beast::http::string_body> req_;
std::shared_ptr<habboy_hw_iface::WebsocketServer> p_ws_server_;
void fail(error_code ec, char const* what);
void on_read(error_code ec, std::size_t);
void on_write(error_code ec, std::size_t, bool close);
public:
http_session(tcp::socket socket, std::shared_ptr<habboy_hw_iface::WebsocketServer> p_ws_server);
void run();
};
} //ns

Wyświetl plik

@ -0,0 +1,80 @@
#include "listener.h"
#include "http_session.h"
#include <iostream>
namespace habboy_hw_iface
{
listener::listener(net::io_context& ioc, tcp::endpoint endpoint, habboy_hw_iface::WebsocketServer& ws_server)
: acceptor_(ioc) , socket_(ioc), p_ws_server_(&ws_server)
{
error_code ec;
acceptor_.open(endpoint.protocol(), ec);
if(ec)
{
fail(ec, "open");
return;
}
acceptor_.set_option(net::socket_base::reuse_address(true));
if(ec)
{
fail(ec, "set_option");
return;
}
acceptor_.bind(endpoint, ec);
if(ec)
{
fail(ec, "bind");
return;
}
acceptor_.listen(
net::socket_base::max_listen_connections, ec);
if(ec)
{
fail(ec, "listen");
return;
}
}
void listener::run()
{
acceptor_.async_accept(
socket_,
[self = shared_from_this()](error_code ec)
{
self->on_accept(ec);
});
}
// Report a failure
void listener::fail(error_code ec, char const* what)
{
if(ec == net::error::operation_aborted)
return;
std::cerr << what << ": " << ec.message() << "\n";
}
void listener::on_accept(error_code ec)
{
if(ec)
return fail(ec, "accept");
else
std::make_shared<http_session>(
std::move(socket_), p_ws_server_
)->run(); // moved-from socket is still valid
// Accept another connection
acceptor_.async_accept(
socket_,
[self = shared_from_this()](error_code ec)
{
self->on_accept(ec);
});
}
} //ns

Wyświetl plik

@ -0,0 +1,31 @@
#pragma once
#include <memory>
#include <string>
#include <boost/asio.hpp>
#include "ws_server.h"
namespace net = boost::asio; // namespace asio
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
using error_code = boost::system::error_code; // from <boost/system/error_code.hpp>
namespace habboy_hw_iface
{
class listener : public std::enable_shared_from_this<listener>
{
tcp::acceptor acceptor_;
tcp::socket socket_;
std::shared_ptr<habboy_hw_iface::WebsocketServer> p_ws_server_;
void fail(error_code ec, char const* what);
void on_accept(error_code ec);
public:
listener(net::io_context& ioc, tcp::endpoint endpoint, habboy_hw_iface::WebsocketServer& ws_server);
void run();
};
} //ns

Wyświetl plik

@ -0,0 +1,105 @@
#include <string>
#include <iostream>
#include <thread>
#include <chrono>
#include "program_options.h"
#include "console_colors.h"
#include "GLOBALS.h"
#include "git_repo_sha1.h"
#include "ws_server.h"
#include "hb_serial.h"
#include "msg_broker.h"
#include "GpsState.h"
bool G_KEEP_RUNNING;
int MAIN(int argc, char** argv)
{
using namespace std;
using namespace habboy_hw_iface;
cout<<"git version: "<<g_GIT_SHA1<<endl;
// setup GLOBALS
//
prog_opts(argc, argv);
cout<<"Current Options: "<<endl;
GLOBALS::Print();
G_KEEP_RUNNING = 1;
// signals
//
signal( SIGINT, [](int){G_KEEP_RUNNING = 0; exit(0);} );
signal( SIGILL, [](int){G_KEEP_RUNNING = 0; exit(0);} );
signal( SIGFPE, [](int){G_KEEP_RUNNING = 0; exit(0);} );
signal( SIGSEGV, [](int){G_KEEP_RUNNING = 0; exit(0);} );
signal( SIGTERM, [](int){G_KEEP_RUNNING = 0; exit(0);} );
signal( SIGABRT, [](int){G_KEEP_RUNNING = 0; exit(0);} );
// MAIN THREADS
//
std::unordered_set<thread*> threads;
// websocket server
WebsocketServer ws_server(GLOBALS::get().par_.ws_host_, GLOBALS::get().par_.ws_port_);
threads.emplace( new thread(
[&ws_server]() { ws_server(); }
) );
// message broker
MessageBroker msg_broker(ws_server);
threads.emplace( new thread(
[&msg_broker]() { msg_broker(); }
) );
// serial connection -- use 'msg_broker.push()' as callback
SerialConnection srl( GLOBALS::get().par_.serial_, GLOBALS::get().par_.baud_ );
srl.add_callback(
[&msg_broker](const std::string& msg) { msg_broker.push(msg); }
);
threads.emplace( new thread(
[&srl]() { srl(); }
) );
// print some info
/*
threads.emplace( new thread(
[]()
{
while(G_KEEP_RUNNING)
{
this_thread::sleep_for(std::chrono::milliseconds(1000));
cout<<GLOBALS::get().gps_.to_str()<<endl;
}
}
));
*/
// finish
//
for(auto t : threads)
t->join();
return 0;
}
int main(int argc, char** argv)
{
return MAIN(argc,argv);
}

Wyświetl plik

@ -0,0 +1,126 @@
#include <msg_broker.h>
#include <thread>
#include <mutex>
#include <chrono>
#include <iostream>
#include "GLOBALS.h"
namespace habboy_hw_iface
{
MessageBroker::MessageBroker(habboy_hw_iface::WebsocketServer& ws_server)
{
p_ws_server_.reset(&ws_server);
}
void MessageBroker::push(std::string msg)
{
using Ms = std::chrono::milliseconds;
/*
if( msg_que_mtx_.try_lock_for(Ms(100)) )
{
std::lock_guard<std::mutex> _lock(msg_que_mtx_);
msg_que_.push(msg);
msg_que_mtx_.unlock();
}
else
{
std::cout<<"push timed out: "<<msg<<std::endl;
}
*/
{
std::lock_guard<std::mutex> _lock(msg_que_mtx_);
msg_que_.push(msg);
}
msg_que_cv_.notify_one();
}
void MessageBroker::operator()()
{
while(keep_running_)
{
using namespace std;
using Ms = std::chrono::milliseconds;
// this_thread::sleep_for(std::chrono::milliseconds(100));
queue<string> msgs;
/*
if( msg_que_mtx_.try_lock_for(Ms(1000)) )
{
msg_que_cv_.wait( msg_que_mtx_ );
msgs = std::move(msg_que_);
msg_que_mtx_.unlock();
}
else
{
std::cout<<"consume timed out."<<std::endl;
}
*/
{
std::unique_lock<std::mutex> lock_(msg_que_mtx_);
msg_que_cv_.wait(lock_);
msgs = std::move(msg_que_);
lock_.unlock();
msg_que_cv_.notify_one();
}
while(msgs.size())
{
bool handled = handle_msg( msgs.front() );
msgs.pop();
}
}
}
bool MessageBroker::handle_msg(const std::string msg)
{
using namespace std;
// p_ws_server_->sessions_send(msg);
auto type_split = msg.find("::");
if(type_split == string::npos)
return false;
string m_type = msg.substr(0, type_split);
string m_body = msg.substr(type_split+2);
if(m_type == "gps")
{
GpsState _gps = GLOBALS::get().gps_;
_gps.from_str(m_body);
_gps.alt /= 1000;
_gps.altmsl /= 1000;
_gps.heading /= 1000;
GLOBALS::get().gps_ = _gps;
p_ws_server_->sessions_send( "gps::" + _gps.to_str() );
}
else
{
// unknown -- just send
p_ws_server_->sessions_send( msg );
}
return true;
}
} //ns

Wyświetl plik

@ -0,0 +1,41 @@
#pragma once
#include <string>
#include <queue>
#include <vector>
#include <mutex>
#include <condition_variable>
#include "ws_server.h"
#include "GpsState.h"
namespace habboy_hw_iface
{
class MessageBroker
{
public:
MessageBroker() = delete;
MessageBroker(const MessageBroker&) = delete;
MessageBroker& operator=(const MessageBroker&) = delete;
MessageBroker(habboy_hw_iface::WebsocketServer& ws_server);
void push(std::string msg);
void operator()();
void Stop() { keep_running_=false; }
private:
std::queue<std::string> msg_que_;
// std::timed_mutex msg_que_mtx_;
std::mutex msg_que_mtx_;
std::condition_variable msg_que_cv_;
bool keep_running_ = true;
std::shared_ptr<habboy_hw_iface::WebsocketServer> p_ws_server_;
bool handle_msg(const std::string msg);
};
} //ns

Wyświetl plik

@ -0,0 +1,117 @@
#include <string>
#include <iostream>
#include <fstream>
#include <regex>
#include <boost/program_options.hpp>
#include "console_colors.h"
#include "GLOBALS.h"
#include "hb_serial.h"
void prog_opts(int ac, char* av[])
{
namespace po = boost::program_options;
using namespace std;
using namespace habboy_hw_iface;
try
{
po::options_description generic("CLI opts");
generic.add_options()
("help", "Display help message")
("wsport", po::value<string>(), "websocket Port, example: --wsport 127.0.0.1:5565")
("serial", po::value<string>(), "arduino serial port. defaults to /dev/ttyUSB0")
("baud", po::value<string>(), "Serial Baud speed - defaults to 115200")
;
po::options_description cli_options("Command Line Interface options");
cli_options.add(generic);
string config_file;
cli_options.add_options()
("config", po::value<string>(&config_file), "Config file.");
po::options_description file_options;
file_options.add(generic);
po::variables_map vm;
store( po::command_line_parser(ac, av).options(cli_options).allow_unregistered().run(), vm );
notify(vm);
if(vm.count("help"))
{
cout<<cli_options<<endl;
exit(0);
}
if(config_file != "")
{
ifstream ifs(config_file.c_str());
if (!ifs)
{
cout << "Can not open config file: " << config_file << endl;
}
else
{
cout<<C_RED<<"Reading config from file "<<config_file<<C_OFF<<endl;
store(parse_config_file(ifs, file_options, 1), vm);
notify(vm);
}
}
if (vm.count("wsport")) // [host:][port]
{
smatch match;
regex_match( vm["wsport"].as<string>(), match, std::regex(R"_(([\w\.]*)(\:?)(\d*))_") );
if(match.size() == 4)
{
if(match[2] == "" && match[3] == "") // special case when only port is given: --port 5565
{
GLOBALS::get().par_.ws_port_ = stoi(match[1]);
}
else
{
if(match[1] != "") GLOBALS::get().par_.ws_host_ = match[1];
if(match[3] != "") GLOBALS::get().par_.ws_port_ = stoi(match[3]);
}
}
}
if (vm.count("serial"))
{
GLOBALS::get().par_.serial_ = vm["serial"].as<string>();
}
if (vm.count("baud"))
{
std::string b = vm["baud"].as<string>();
if(b == "0") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b0;
if(b == "50") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b50;
if(b == "75") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b75;
if(b == "110") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b110;
if(b == "134") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b134;
if(b == "150") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b150;
if(b == "200") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b200;
if(b == "300") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b300;
if(b == "600") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b600;
if(b == "1200") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b1200;
if(b == "1800") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b1800;
if(b == "2400") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b2400;
if(b == "4800") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b4800;
if(b == "9600") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b9600;
if(b == "19200") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b19200;
if(b == "38400") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b38400;
if(b == "57600") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b57600;
if(b == "115200") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b115200;
if(b == "230400") GLOBALS::get().par_.baud_ = SerialConnection::Baud::b230400;
}
}
catch(exception& e)
{
cout << e.what() << "\n";
}
GLOBALS::DumpToFile("./habboy_hw_iface.opts");
}

Wyświetl plik

@ -0,0 +1,3 @@
#pragma once
void prog_opts(int ac, char* av[]);

Plik diff jest za duży Load Diff

Wyświetl plik

@ -0,0 +1,429 @@
///////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2008-2010, Sony Pictures Imageworks Inc
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// Neither the name of the organization Sony Pictures Imageworks nor the
// names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS
// IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
// TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
// PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER
// OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
///////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDED_PYSTRING_H
#define INCLUDED_PYSTRING_H
#include <string>
#include <vector>
namespace pystring
{
//////////////////////////////////////////////////////////////////////////////////////////////
/// @mainpage pystring
///
/// This is a set of functions matching the interface and behaviors of python string methods
/// (as of python 2.3) using std::string.
///
/// Overlapping functionality ( such as index and slice/substr ) of std::string is included
/// to match python interfaces.
///
//////////////////////////////////////////////////////////////////////////////////////////////
/// @defgroup functions pystring
/// @{
#define MAX_32BIT_INT 2147483647
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string with only its first character capitalized.
///
std::string capitalize( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return centered in a string of length width. Padding is done using spaces.
///
std::string center( const std::string & str, int width );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return the number of occurrences of substring sub in string S[start:end]. Optional
/// arguments start and end are interpreted as in slice notation.
///
int count( const std::string & str, const std::string & substr, int start = 0, int end = MAX_32BIT_INT);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return True if the string ends with the specified suffix, otherwise return False. With
/// optional start, test beginning at that position. With optional end, stop comparing at that position.
///
bool endswith( const std::string & str, const std::string & suffix, int start = 0, int end = MAX_32BIT_INT );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string where all tab characters are expanded using spaces. If tabsize
/// is not given, a tab size of 8 characters is assumed.
///
std::string expandtabs( const std::string & str, int tabsize = 8);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return the lowest index in the string where substring sub is found, such that sub is
/// contained in the range [start, end). Optional arguments start and end are interpreted as
/// in slice notation. Return -1 if sub is not found.
///
int find( const std::string & str, const std::string & sub, int start = 0, int end = MAX_32BIT_INT );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Synonym of find right now. Python version throws exceptions. This one currently doesn't
///
int index( const std::string & str, const std::string & sub, int start = 0, int end = MAX_32BIT_INT );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return true if all characters in the string are alphanumeric and there is at least one
/// character, false otherwise.
///
bool isalnum( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return true if all characters in the string are alphabetic and there is at least one
/// character, false otherwise
///
bool isalpha( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return true if all characters in the string are digits and there is at least one
/// character, false otherwise.
///
bool isdigit( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return true if all cased characters in the string are lowercase and there is at least one
/// cased character, false otherwise.
///
bool islower( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return true if there are only whitespace characters in the string and there is at least
/// one character, false otherwise.
///
bool isspace( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return true if the string is a titlecased string and there is at least one character,
/// i.e. uppercase characters may only follow uncased characters and lowercase characters only
/// cased ones. Return false otherwise.
///
bool istitle( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return true if all cased characters in the string are uppercase and there is at least one
/// cased character, false otherwise.
///
bool isupper( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a string which is the concatenation of the strings in the sequence seq.
/// The separator between elements is the str argument
///
std::string join( const std::string & str, const std::vector< std::string > & seq );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return the string left justified in a string of length width. Padding is done using
/// spaces. The original string is returned if width is less than str.size().
///
std::string ljust( const std::string & str, int width );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string converted to lowercase.
///
std::string lower( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string with leading characters removed. If chars is omitted or None,
/// whitespace characters are removed. If given and not "", chars must be a string; the
/// characters in the string will be stripped from the beginning of the string this method
/// is called on (argument "str" ).
///
std::string lstrip( const std::string & str, const std::string & chars = "" );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string, concatenated N times, together.
/// Corresponds to the __mul__ operator.
///
std::string mul( const std::string & str, int n);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Split the string around first occurance of sep.
/// Three strings will always placed into result. If sep is found, the strings will
/// be the text before sep, sep itself, and the remaining text. If sep is
/// not found, the original string will be returned with two empty strings.
///
void partition( const std::string & str, const std::string & sep, std::vector< std::string > & result );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string with all occurrences of substring old replaced by new. If
/// the optional argument count is given, only the first count occurrences are replaced.
///
std::string replace( const std::string & str, const std::string & oldstr, const std::string & newstr, int count = -1);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return the highest index in the string where substring sub is found, such that sub is
/// contained within s[start,end]. Optional arguments start and end are interpreted as in
/// slice notation. Return -1 on failure.
///
int rfind( const std::string & str, const std::string & sub, int start = 0, int end = MAX_32BIT_INT );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Currently a synonym of rfind. The python version raises exceptions. This one currently
/// does not
///
int rindex( const std::string & str, const std::string & sub, int start = 0, int end = MAX_32BIT_INT );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return the string right justified in a string of length width. Padding is done using
/// spaces. The original string is returned if width is less than str.size().
///
std::string rjust( const std::string & str, int width);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Split the string around last occurance of sep.
/// Three strings will always placed into result. If sep is found, the strings will
/// be the text before sep, sep itself, and the remaining text. If sep is
/// not found, the original string will be returned with two empty strings.
///
void rpartition( const std::string & str, const std::string & sep, std::vector< std::string > & result );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string with trailing characters removed. If chars is "", whitespace
/// characters are removed. If not "", the characters in the string will be stripped from the
/// end of the string this method is called on.
///
std::string rstrip( const std::string & str, const std::string & chars = "" );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Fills the "result" list with the words in the string, using sep as the delimiter string.
/// If maxsplit is > -1, at most maxsplit splits are done. If sep is "",
/// any whitespace string is a separator.
///
void split( const std::string & str, std::vector< std::string > & result, const std::string & sep = "", int maxsplit = -1);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Fills the "result" list with the words in the string, using sep as the delimiter string.
/// Does a number of splits starting at the end of the string, the result still has the
/// split strings in their original order.
/// If maxsplit is > -1, at most maxsplit splits are done. If sep is "",
/// any whitespace string is a separator.
///
void rsplit( const std::string & str, std::vector< std::string > & result, const std::string & sep = "", int maxsplit = -1);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a list of the lines in the string, breaking at line boundaries. Line breaks
/// are not included in the resulting list unless keepends is given and true.
///
void splitlines( const std::string & str, std::vector< std::string > & result, bool keepends = false );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return True if string starts with the prefix, otherwise return False. With optional start,
/// test string beginning at that position. With optional end, stop comparing string at that
/// position
///
bool startswith( const std::string & str, const std::string & prefix, int start = 0, int end = MAX_32BIT_INT );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string with leading and trailing characters removed. If chars is "",
/// whitespace characters are removed. If given not "", the characters in the string will be
/// stripped from the both ends of the string this method is called on.
///
std::string strip( const std::string & str, const std::string & chars = "" );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string with uppercase characters converted to lowercase and vice versa.
///
std::string swapcase( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a titlecased version of the string: words start with uppercase characters,
/// all remaining cased characters are lowercase.
///
std::string title( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string where all characters occurring in the optional argument
/// deletechars are removed, and the remaining characters have been mapped through the given
/// translation table, which must be a string of length 256.
///
std::string translate( const std::string & str, const std::string & table, const std::string & deletechars = "");
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a copy of the string converted to uppercase.
///
std::string upper( const std::string & str );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return the numeric string left filled with zeros in a string of length width. The original
/// string is returned if width is less than str.size().
///
std::string zfill( const std::string & str, int width );
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief function matching python's slice functionality.
///
std::string slice( const std::string & str, int start = 0, int end = MAX_32BIT_INT);
///
/// @ }
///
namespace os
{
namespace path
{
// All of the function below have three versions.
// Example:
// join(...)
// join_nt(...)
// join_posix(...)
//
// The regular function dispatches to the other versions - based on the OS
// at compile time - to match the result you'd get from the python
// interepreter on the same operating system
//
// Should you want to 'lock off' to a particular version of the string
// manipulation across *all* operating systems, use the version with the
// _OS you are interested in. I.e., you can use posix style path joining,
// even on Windows, with join_posix.
//
// The naming, (nt, posix) matches the cpython source implementation.
//////////////////////////////////////////////////////////////////////////////////////////////
/// @defgroup functions pystring::os::path
/// @{
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return the base name of pathname path. This is the second half of the pair returned
/// by split(path). Note that the result of this function is different from the Unix basename
/// program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an
/// empty string ('').
std::string basename(const std::string & path);
std::string basename_nt(const std::string & path);
std::string basename_posix(const std::string & path);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return the directory name of pathname path. This is the first half of the pair
/// returned by split(path).
std::string dirname(const std::string & path);
std::string dirname_nt(const std::string & path);
std::string dirname_posix(const std::string & path);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return True if path is an absolute pathname. On Unix, that means it begins with a
/// slash, on Windows that it begins with a (back)slash after chopping off a potential drive
/// letter.
bool isabs(const std::string & path);
bool isabs_nt(const std::string & path);
bool isabs_posix(const std::string & s);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Return a normalized absolutized version of the pathname path.
///
/// NOTE: This differs from the interface of the python equivalent in that it requires you
/// to pass in the current working directory as an argument.
std::string abspath(const std::string & path, const std::string & cwd);
std::string abspath_nt(const std::string & path, const std::string & cwd);
std::string abspath_posix(const std::string & path, const std::string & cwd);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Join one or more path components intelligently. If any component is an absolute
/// path, all previous components (on Windows, including the previous drive letter, if there
/// was one) are thrown away, and joining continues. The return value is the concatenation of
/// path1, and optionally path2, etc., with exactly one directory separator (os.sep) inserted
/// between components, unless path2 is empty. Note that on Windows, since there is a current
/// directory for each drive, os.path.join("c:", "foo") represents a path relative to the
/// current directory on drive C: (c:foo), not c:\foo.
/// This dispatches based on the compilation OS
std::string join(const std::string & path1, const std::string & path2);
std::string join_nt(const std::string & path1, const std::string & path2);
std::string join_posix(const std::string & path1, const std::string & path2);
std::string join(const std::vector< std::string > & paths);
std::string join_nt(const std::vector< std::string > & paths);
std::string join_posix(const std::vector< std::string > & paths);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Normalize a pathname. This collapses redundant separators and up-level references
/// so that A//B, A/B/, A/./B and A/foo/../B all become A/B. It does not normalize the case
/// (use normcase() for that). On Windows, it converts forward slashes to backward slashes.
/// It should be understood that this may change the meaning of the path if it contains
/// symbolic links!
std::string normpath(const std::string & path);
std::string normpath_nt(const std::string & path);
std::string normpath_posix(const std::string & path);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Split the pathname path into a pair, (head, tail) where tail is the last pathname
/// component and head is everything leading up to that. The tail part will never contain a
/// slash; if path ends in a slash, tail will be empty. If there is no slash in path, head
/// will be empty. If path is empty, both head and tail are empty. Trailing slashes are
/// stripped from head unless it is the root (one or more slashes only). In all cases,
/// join(head, tail) returns a path to the same location as path (but the strings may
/// differ).
void split(std::string & head, std::string & tail, const std::string & path);
void split_nt(std::string & head, std::string & tail, const std::string & path);
void split_posix(std::string & head, std::string & tail, const std::string & path);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Split the pathname path into a pair (drive, tail) where drive is either a drive
/// specification or the empty string. On systems which do not use drive specifications,
/// drive will always be the empty string. In all cases, drive + tail will be the same as
/// path.
void splitdrive(std::string & drivespec, std::string & pathspec, const std::string & path);
void splitdrive_nt(std::string & drivespec, std::string & pathspec, const std::string & p);
void splitdrive_posix(std::string & drivespec, std::string & pathspec, const std::string & path);
//////////////////////////////////////////////////////////////////////////////////////////////
/// @brief Split the pathname path into a pair (root, ext) such that root + ext == path, and
/// ext is empty or begins with a period and contains at most one period. Leading periods on
/// the basename are ignored; splitext('.cshrc') returns ('.cshrc', '').
void splitext(std::string & root, std::string & ext, const std::string & path);
void splitext_nt(std::string & root, std::string & ext, const std::string & path);
void splitext_posix(std::string & root, std::string & ext, const std::string & path);
///
/// @ }
///
} // namespace path
} // namespace os
} // namespace pystring
#endif

Wyświetl plik

@ -0,0 +1,38 @@
#!/usr/bin/python
import sys
import time
import serial
import random
import math
import time
s = serial.Serial(sys.argv[1])
def gps_loop():
i = 0
while(1):
time.sleep(1)
i += 1
try:
lat = 52.0 + .01 * math.sin(.1 * i)
lon = 21.0 + .01 * math.cos(.1 * i)
speed = 100.0 + 20.0 * math.cos(.1 * i)
sats = random.randrange(4,9)
msg = 'gps::' + 'time=%s,lat=%f,lon=%f,alt=180000,altmsl=190000,sats=%d,speed=%f,heading=160000' % ( time.strftime("%H%M%S", time.gmtime()), lat, lon, sats, speed )
print msg
s.write(msg + "\n")
except KeyboardInterrupt:
return
def cycle_tabs(_dir):
msg = "tab::cycle=" + _dir
s.write(msg + "\n")
if __name__ == "__main__":
gps_loop()
# cycle_tabs( sys.argv[2] )

Wyświetl plik

@ -0,0 +1,4 @@
#!/bin/sh
socat -d -d pty,raw,echo=0 pty,raw,echo=0

Wyświetl plik

@ -0,0 +1,99 @@
#include "websocket_session.h"
#include "GLOBALS.h"
namespace habboy_hw_iface
{
websocket_session::websocket_session(
tcp::socket socket,
std::shared_ptr<habboy_hw_iface::WebsocketServer> p_ws_server )
: ws_(std::move(socket))
{
p_ws_server_ = p_ws_server;
}
websocket_session::~websocket_session()
{
// Remove this session from the list of active sessions
// state_->leave(*this);
p_ws_server_->session_delete(*this);
}
void websocket_session::fail(error_code ec, char const* what)
{
if( ec == net::error::operation_aborted ||
ec == boost::beast::websocket::error::closed)
return;
std::cerr << what << ": " << ec.message() << "\n";
}
void websocket_session::on_accept(error_code ec)
{
if(ec)
return fail(ec, "accept");
p_ws_server_->session_add(*this);
// Read a message
ws_.async_read(
buffer_,
[sp = shared_from_this()](
error_code ec, std::size_t bytes)
{
sp->on_read(ec, bytes);
});
}
void websocket_session::on_read(error_code ec, std::size_t)
{
if(ec)
return fail(ec, "read");
// GLOBALS::get().sessions_send( boost::beast::buffers_to_string(buffer_.data()) );
p_ws_server_->sessions_send( boost::beast::buffers_to_string( buffer_.data()) );
std::string msg = boost::beast::buffers_to_string( buffer_.data() );
std::cout<<"received message: "<<msg<<std::endl;
buffer_.consume(buffer_.size());
ws_.async_read(
buffer_,
[sp = shared_from_this()](
error_code ec, std::size_t bytes)
{
sp->on_read(ec, bytes);
});
}
void websocket_session::send(std::shared_ptr<std::string const> const& ss)
{
queue_.push_back(ss);
if(queue_.size() > 1)
return;
ws_.async_write(
net::buffer(*queue_.front()),
[sp = shared_from_this()](error_code ec, std::size_t bytes)
{
sp->on_write(ec, bytes);
});
}
void websocket_session::on_write(error_code ec, std::size_t)
{
if(ec)
return fail(ec, "write");
queue_.erase(queue_.begin());
if(! queue_.empty())
ws_.async_write(
net::buffer(*queue_.front()),
[sp = shared_from_this()](error_code ec, std::size_t bytes)
{
sp->on_write(ec, bytes);
});
}
} // ns

Wyświetl plik

@ -0,0 +1,54 @@
#pragma once
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include "ws_server.h"
namespace habboy_hw_iface
{
namespace net = boost::asio; // namespace asio
using tcp = net::ip::tcp; // from <boost/asio/ip/tcp.hpp>
using error_code = boost::system::error_code; // from <boost/system/error_code.hpp>
class websocket_session : public std::enable_shared_from_this<websocket_session>
{
boost::beast::flat_buffer buffer_;
boost::beast::websocket::stream<tcp::socket> ws_;
std::vector<std::shared_ptr<std::string const>> queue_;
std::shared_ptr<habboy_hw_iface::WebsocketServer> p_ws_server_;
void fail(error_code ec, char const* what);
void on_accept(error_code ec);
void on_read(error_code ec, std::size_t bytes_transferred);
void on_write(error_code ec, std::size_t bytes_transferred);
public:
websocket_session(tcp::socket socket, std::shared_ptr<habboy_hw_iface::WebsocketServer> p_ws_server);
~websocket_session();
template<class Body, class Allocator>
void run(boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>> req);
void send(std::shared_ptr<std::string const> const& i_msg);
};
template<class Body, class Allocator>
void websocket_session::run(boost::beast::http::request<Body, boost::beast::http::basic_fields<Allocator>> req)
{
ws_.async_accept(
req,
std::bind(
&websocket_session::on_accept,
shared_from_this(),
std::placeholders::_1));
}
} //ns

Wyświetl plik

@ -0,0 +1,37 @@
#include "ws_server.h"
#include "listener.h"
#include "websocket_session.h"
namespace habboy_hw_iface
{
void WebsocketServer::operator()()
{
using namespace std;
using tcp = boost::asio::ip::tcp;
auto const address = boost::asio::ip::make_address( host_ );
auto const port = static_cast<unsigned short>( port_ );
make_shared<habboy_hw_iface::listener>(
ioc_,
tcp::endpoint{address, port},
*this
)->run();
ioc_.run();
}
void WebsocketServer::sessions_send (std::string message)
{
auto const ss = std::make_shared<std::string const>(std::move(message));
{
std::lock_guard<std::mutex> lock(sessions_mtx_);
for(auto session : sessions_)
session->send(ss);
}
}
} //ns

Wyświetl plik

@ -0,0 +1,54 @@
#pragma once
#include <string>
#include <thread>
#include <mutex>
#include <unordered_set>
#include <boost/asio/ip/tcp.hpp>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/signal_set.hpp>
// #include "websocket_session.h"
/*
using boost::asio::ip::tcp;
namespace beast = boost::beast;
namespace websocket = boost::beast::websocket;
*/
namespace habboy_hw_iface
{
class websocket_session;
class WebsocketServer : public std::enable_shared_from_this<WebsocketServer>
{
public:
WebsocketServer() = delete;
WebsocketServer(const WebsocketServer&) = delete;
WebsocketServer& operator=(const WebsocketServer&) = delete;
WebsocketServer(std::string host, unsigned int port) : host_(host), port_(port) {}
void operator()();
// sessions
void session_add (habboy_hw_iface::websocket_session& session) { sessions_.insert(&session); }
void session_delete (habboy_hw_iface::websocket_session& session) { sessions_.erase(&session); }
void sessions_send (std::string message);
private:
std::string host_{"0.0.0.0"};
unsigned int port_{5565};
boost::asio::io_context ioc_{1};
// sessions
std::unordered_set<habboy_hw_iface::websocket_session*> sessions_;
std::mutex sessions_mtx_;
};
} //ns

Wyświetl plik

@ -0,0 +1,36 @@
<!DOCTYPE html>
<meta charset="utf-8" />
<script src="js/ws_client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<head>
<style>
body, html {
height: 100%;
width: 100%;
}
div {
font-family: Tahoma, Verdana, Segoe, sans-serif;
}
</style>
</head>
<body>
<div id="ws_client_info"></div>
<div id="ws_client_debug"></div>
</body>
<script language="javascript" type="text/javascript">
function habboy_hw_iface_ws_test_client_init()
{
OpenConnection("127.0.0.1:5565");
}
window.addEventListener("load", habboy_hw_iface_ws_test_client_init, false);
</script>

Wyświetl plik

@ -0,0 +1,110 @@
var G_HD_WEBSOCKET;
var G_HD_CONNECTED = 0;
function debug_print()
{
console.debug(arguments);
document.getElementById("ws_client_debug").innerHTML = "";
for (i = 0; i < arguments.length; i++)
document.getElementById("ws_client_debug").innerHTML += arguments[i] + " ";
}
function OpenConnection(endpoint)
{
if(G_HD_CONNECTED)
return;
var server = endpoint;
console.debug("Connecting to ", server, " ...");
G_HD_WEBSOCKET = new WebSocket("ws://" + server);
G_HD_WEBSOCKET.binaryType = 'arraybuffer'; // or 'blob'
G_HD_WEBSOCKET.onopen = function(evt) { ws_onOpen(evt) };
G_HD_WEBSOCKET.onclose = function(evt) { ws_onClose(evt) };
G_HD_WEBSOCKET.onmessage = function(evt) { ws_onMessage(evt) };
G_HD_WEBSOCKET.onerror = function(evt) { ws_onError(evt) };
}
function ws_onClose(evt)
{
G_HD_CONNECTED = 0;
debug_print("DISCONNECTED");
setTimeout(function () { OpenConnection(); }, 5000);
}
function ws_onError(evt)
{
debug_print("ws_onError: ", evt.data);
}
function ws_onOpen(evt)
{
G_HD_CONNECTED = 1;
debug_print("ws_onOpen: ", "Connected.");
G_HD_WEBSOCKET.send("hi");
SendCommand("info:gps");
console.debug("ws_onOpen: init refresh.");
}
function ws_onMessage(evt)
{
if(!G_HD_CONNECTED)
{
debug_print("ws_onMessage: not connected.");
return;
}
// console.debug("ON_MSG", evt);
if(typeof evt.data === "string")
{
HandleMessage(evt.data)
}
else if(evt.data instanceof ArrayBuffer)
{
debug_print("got bin data");
}
else
{
debug_print("ws_onMessage: unknown data type.");
return;
}
}
function SendCommand(i_cmd)
{
if(!G_HD_CONNECTED)
{
debug_print("SendCommand: not connected.");
return;
}
var msg = "cmd::" + i_cmd;
// debug_print("SendCommand: ", msg);
G_HD_WEBSOCKET.send(msg);
}
function HandleMessage(i_data)
{
if(!G_HD_CONNECTED)
{
debug_print("HandleMessage: not connected.");
return;
}
if( !i_data.startsWith("cmd::info:liveprint") )
debug_print("Received Message: ", i_data);
return false;
}

Wyświetl plik

@ -0,0 +1,3 @@
Example usage and config of tilemaker
How to use tilemaker: https://github.com/ogre/tilemaker_config

Wyświetl plik

@ -0,0 +1,37 @@
{
"layers": {
"admin": {
"source": "../data/boundaries/export3.shp",
"source_columns": [
"admin_level"
],
"minzoom": 5,
"maxzoom": 10,
"simplify_below": 10,
"simplify_length": 100,
"simplify_level": 0.0035,
"simplify_ratio": 3
}
},
"settings": {
"minzoom": 5,
"maxzoom": 10,
"basezoom": 10,
"include_ids": false,
"name": "HAB",
"version": "1.0",
"description": "HAB",
"compress": "none",
"metadata": {
"json": {
"vector_layers": [
{
"id": "admin",
"description": "admin",
"fields": {}
}
]
}
}
}
}

Wyświetl plik

@ -0,0 +1,24 @@
node_keys = {
}
function init_function()
end
function exit_function()
end
function node_function(node)
end
function way_function(way)
-- something has to be written
-- local boundary = way:Find("boundary")
-- if boundary ~= nil and boundary == "administrative" then
-- local admin_level = way:Find("admin_level")
-- if admin_level ~= nil and admin_level ~= "" then
-- layer = "unused"
-- way:Layer(layer, false)
-- end -- admin level
-- end
end

Wyświetl plik

@ -0,0 +1,39 @@
{
"layers": {
"aeroway": {
"minzoom": 9,
"maxzoom": 14,
"simplify_below": 13,
"simplify_length": 10,
"simplify_ratio": 3
},
"aeroway_other": {
"minzoom": 9,
"maxzoom": 14,
"simplify_below": 13,
"simplify_length": 10,
"simplify_ratio": 3
}
},
"settings": {
"minzoom": 8,
"maxzoom": 14,
"basezoom": 14,
"include_ids": false,
"name": "HAB",
"version": "1.0",
"description": "HAB",
"compress": "none",
"metadata": {
"json": {
"vector_layers": [
{
"id": "aeroway",
"description": "aeroway",
"fields": {}
}
]
}
}
}
}

Wyświetl plik

@ -0,0 +1,83 @@
node_keys = {}
G_DEFAULT = 0
G_COUNTS = {}
function zoom_tile_area(latitude_degrees, zoom_level)
earth_equatorial_circumference = 40075016.686 -- meters
latitude_radians = 3.14159265359 * latitude_degrees / 180.0
tile_width = earth_equatorial_circumference * math.cos(latitude_radians) / (2^zoom_level)
return tile_width*tile_width
end
-- store m2 area for one tile on each zoom level
ZOOM_TILES_AREA = {}
function init_function()
for i=1,16 do
ZOOM_TILES_AREA[i] = zoom_tile_area(52.0, i)
print(ZOOM_TILES_AREA[i])
end
end
local function is_in (val, tab)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function get_min_zoom(in_area)
local min_zoom = 1
for _z=15,1,-1 do
if in_area < (0.01 * ZOOM_TILES_AREA[_z]) then
return _z
end
end
return min_zoom
end
function exit_function()
for _k,_v in pairs(G_COUNTS)
do
print("\n")
print(_k)
for k,v in pairs(_v)
do
print("\t", k, v)
end
end
end
function node_function(node)
end
function way_function(way)
local name = way:Find("name");
-- aeroway
local aeroway = way:Find("aeroway")
if aeroway ~= nil and aeroway ~= "" then
local class = aeroway
if G_COUNTS["aeroway"] == nil then G_COUNTS["aeroway"] = {} end
if G_COUNTS["aeroway"][aeroway] == nil then G_COUNTS["aeroway"][aeroway] = 0 end
G_COUNTS["aeroway"][aeroway] = G_COUNTS["aeroway"][aeroway] + 1
if is_in( aeroway, { "aerodrome", "apron", "heliport", "runway", "terminal", "hangar"} )then
layer = "aeroway"
way:Layer(layer, way:IsClosed())
way:Attribute("class", aeroway)
way:MinZoom( get_min_zoom(way:Area()) )
if name ~= nil and name ~= "" then way:Attribute("name",name) end
end
end
end

Wyświetl plik

@ -0,0 +1,29 @@
{
"layers": {
"building": {
"minzoom": 15,
"maxzoom": 15
}
},
"settings": {
"minzoom": 15,
"maxzoom": 15,
"basezoom": 15,
"include_ids": false,
"name": "HAB",
"version": "1.0",
"description": "HAB",
"compress": "none",
"metadata": {
"json": {
"vector_layers": [
{
"id": "building",
"description": "building",
"fields": {}
}
]
}
}
}
}

Wyświetl plik

@ -0,0 +1,85 @@
node_keys = {}
G_DEFAULT = 0
G_COUNTS = {}
function zoom_tile_area(latitude_degrees, zoom_level)
earth_equatorial_circumference = 40075016.686 -- meters
latitude_radians = 3.14159265359 * latitude_degrees / 180.0
tile_width = earth_equatorial_circumference * math.cos(latitude_radians) / (2^zoom_level)
return tile_width*tile_width
end
-- store m2 area for one tile on each zoom level
ZOOM_TILES_AREA = {}
function init_function()
for i=1,16 do
ZOOM_TILES_AREA[i] = zoom_tile_area(52.0, i)
print(ZOOM_TILES_AREA[i])
end
end
local function is_in (val, tab)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function get_min_zoom(in_area)
local min_zoom = 1
for _z=15,1,-1 do
if in_area < (0.01 * ZOOM_TILES_AREA[_z]) then
return _z
end
end
return min_zoom
end
function exit_function()
for _k,_v in pairs(G_COUNTS)
do
print("\n")
print(_k)
for k,v in pairs(_v)
do
print("\t", k, v)
end
end
end
function node_function(node)
end
function way_function(way)
local name = way:Find("name");
-- building
local building = way:Find("building")
if building ~= nil and building ~= "" then
if G_COUNTS["building"] == nil then G_COUNTS["building"] = {} end
if G_COUNTS["building"][building] == nil then G_COUNTS["building"][building] = 0 end
G_COUNTS["building"][building] = G_COUNTS["building"][building] + 1
local layer = "building"
way:Layer(layer, true)
way:Attribute("class", building)
if name ~= nil and name ~= "" then way:Attribute("name",name) end
local height = way:Find("height");
if height ~= nil and height ~= "" then way:Attribute("height",height) end
local min_height = way:Find("min_height");
if min_height ~= nil and min_height ~= "" then way:Attribute("min_height",min_height) end
end
end

Wyświetl plik

@ -0,0 +1,33 @@
{
"layers": {
"place_label": {
"minzoom": 6,
"maxzoom": 15
},
"road_label": {
"minzoom": 6,
"maxzoom": 15
}
},
"settings": {
"minzoom": 5,
"maxzoom": 15,
"basezoom": 15,
"include_ids": false,
"name": "HAB",
"version": "1.0",
"description": "HAB",
"compress": "none",
"metadata": {
"json": {
"vector_layers": [
{
"id": "labels",
"description": "labels",
"fields": {}
}
]
}
}
}
}

Wyświetl plik

@ -0,0 +1,140 @@
-- https://taginfo.openstreetmap.org/keys
node_keys = {
-- "Aerialway",
-- "Aeroway",
-- "Amenity",
-- "Barrier",
-- "Boundary",
-- "building",
-- "Craft",
-- "Emergency",
-- "Geological",
-- "Highway",
-- "Historic",
-- "Common Landuse Key Values",
-- "Other Landuse Key Values",
-- "Leisure",
-- "Man_made",
-- "Military",
-- "natural",
-- "Office",
"place",
-- "Power",
-- "Public Transport",
-- "Railway",
-- "Route",
-- "Shop",
-- "Sport",
-- "Telecom",
-- "Tourism",
-- "Waterway"
}
G_DEFAULT = 0
G_COUNTS = {}
function init_function()
end
local function is_in (val, tab)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function exit_function()
for _k,_v in pairs(G_COUNTS)
do
print("\n")
print(_k)
for k,v in pairs(_v)
do
print("\t", k, v)
end
end
end
function node_function(node)
local place = node:Find("place")
local capital = node:Find("capital")
local admin_level = node:Find("admin_level")
local name = node:Find("name")
local aeroway = node:Find("aeroway")
-- local shop = node:Find("shop")
-- local amenity = node:Find("amenity")
-- place
if place ~= nil and place ~= "" then
node:Layer("place_label", false)
node:Attribute("name",name)
-- the main field for styling labels for different kinds of places is type.
-- possible values: 'city','town','village','hamlet','suburb','neighbourhood'
node:Attribute("type",place)
--The capital field allows distinct styling of labels or icons for the capitals of countries, regions, or states & provinces.
-- 2=National capital, 3=Regional capital (uncommon), 4=State/provincial capital
if capital ~="" then
if admin_level == 2 then
node:AttributeNumeric("capital",2)
end
if admin_level == 4 then
node:AttributeNumeric("capital",4)
end
end
-- The value number from 0 through 9, where 0 is the large end of the scale (eg New York City).
-- All places other than large cities will have a scalerank of null.
if place == "village" then
node:AttributeNumeric("scalerank",3)
end
if place == "town" then
node:AttributeNumeric("scalerank",5)
end
if place == "suburb" then
node:AttributeNumeric("scalerank",7)
end
if place == "city" then
node:AttributeNumeric("scalerank",9)
end
-- Therefore to reduce the label density to 4 labels per tile, you can add the filter [localrank=1].
node:AttributeNumeric("localrank",1)
-- The ldir field can be used as a hint for label offset directions at lower zoom levels.
node:Attribute("ldir","N")
end
end
function way_function(way)
local name = way:Find("name");
-- road_label layer
local highway = way:Find("highway")
if highway ~= nil and highway ~= "" and name ~= "" then
way:Layer("road_label", false)
way:Attribute("name",name)
local ref = way:Find("ref")
if ref ~= "" then
way:Attribute("ref", ref)
way:AttributeNumeric( "reflen", string.len(ref) )
end
way:AttributeNumeric("osm_id",tonumber(way:Id()))
way:Attribute("shield","default")
way:AttributeNumeric("len", 100)
way:AttributeNumeric("localrank", 3)
--"class","len","localrank","name","name_de","name_en","name_es","name_fr","name_ru","name_zh","osm_id","ref","reflen","shield"
--way:AttributeBoolean("oneway": "false")
if highway=="residential" then way:Attribute("class","street") end
if highway=="primary" or highway=="secondary" or highway=="tertiary" then
way:Attribute("class","main")
end
if highway=="primary_link" or highway=="secondary_link" then
way:Attribute("class","street")
end
end
end

Wyświetl plik

@ -0,0 +1,39 @@
{
"layers": {
"landuse": {
"minzoom": 9,
"maxzoom": 14,
"simplify_below": 13,
"simplify_length": 10,
"simplify_ratio": 3
},
"natural": {
"minzoom": 9,
"maxzoom": 14,
"simplify_below": 13,
"simplify_length": 10,
"simplify_ratio": 3
}
},
"settings": {
"minzoom": 9,
"maxzoom": 14,
"basezoom": 14,
"include_ids": false,
"name": "HAB",
"version": "1.0",
"description": "HAB",
"compress": "none",
"metadata": {
"json": {
"vector_layers": [
{
"id": "roads",
"description": "roads",
"fields": {}
}
]
}
}
}
}

Wyświetl plik

@ -0,0 +1,96 @@
node_keys = {}
G_DEFAULT = 0
G_COUNTS = {}
function zoom_tile_area(latitude_degrees, zoom_level)
earth_equatorial_circumference = 40075016.686 -- meters
latitude_radians = 3.14159265359 * latitude_degrees / 180.0
tile_width = earth_equatorial_circumference * math.cos(latitude_radians) / (2^zoom_level)
return tile_width*tile_width
end
-- store m2 area for one tile on each zoom level
ZOOM_TILES_AREA = {}
function init_function()
for i=1,16 do
ZOOM_TILES_AREA[i] = zoom_tile_area(52.0, i)
print(ZOOM_TILES_AREA[i])
end
end
local function is_in (val, tab)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function get_min_zoom(in_area)
local min_zoom = 1
for _z=15,1,-1 do
if in_area < (0.01 * ZOOM_TILES_AREA[_z]) then
return _z
end
end
return min_zoom
end
function exit_function()
for _k,_v in pairs(G_COUNTS)
do
print("\n")
print(_k)
for k,v in pairs(_v)
do
print("\t", k, v)
end
end
end
function node_function(node)
end
function way_function(way)
local name = way:Find("name");
-- Landuse
local landuse = way:Find("landuse")
if landuse ~= nil and landuse ~= "" then
if G_COUNTS["landuse"] == nil then G_COUNTS["landuse"] = {} end
if G_COUNTS["landuse"][landuse] == nil then G_COUNTS["landuse"][landuse] = 0 end
G_COUNTS["landuse"][landuse] = G_COUNTS["landuse"][landuse] + 1
local layer = "landuse"
way:Layer(layer, way:IsClosed())
way:Attribute("class", landuse)
way:MinZoom( get_min_zoom(way:Area()) )
if name ~= nil and name ~= "" then way:Attribute("name",name) end
end
-- Natural
local natural = way:Find("natural")
if natural ~= nil and natural ~= "" then
if G_COUNTS["natural"] == nil then G_COUNTS["natural"] = {} end
if G_COUNTS["natural"][natural] == nil then G_COUNTS["natural"][natural] = 0 end
G_COUNTS["natural"][natural] = G_COUNTS["natural"][natural] + 1
if is_in( natural, { "wood", "forest", "scrub", "heath", "grassland", "fell", "bare_rock", "scree", "shingle", "sand", "meadow" } ) then
local layer = "natural"
way:Layer(layer, way:IsClosed())
way:Attribute("class", natural)
way:MinZoom( get_min_zoom(way:Area()) )
if name ~= nil and name ~= "" then way:Attribute("name",name) end
end
end
end

Wyświetl plik

@ -0,0 +1,39 @@
{
"layers": {
"roads": {
"minzoom": 5,
"maxzoom": 14,
"simplify_below": 12,
"simplify_level": 0.001,
"simplify_ratio": 2
},
"railways": {
"minzoom": 13,
"maxzoom": 14,
"simplify_below": 13,
"simplify_level": 0.001,
"simplify_ratio": 2
}
},
"settings": {
"minzoom": 5,
"maxzoom": 14,
"basezoom": 14,
"include_ids": false,
"name": "HAB",
"version": "1.0",
"description": "HAB",
"compress": "none",
"metadata": {
"json": {
"vector_layers": [
{
"id": "roads",
"description": "roads",
"fields": {}
}
]
}
}
}
}

Wyświetl plik

@ -0,0 +1,144 @@
-- https://taginfo.openstreetmap.org/keys
node_keys = {}
G_DEFAULT = 0
G_COUNTS = {}
function init_function()
end
function exit_function()
for _k,_v in pairs(G_COUNTS)
do
print("\n")
print(_k)
for k,v in pairs(_v)
do
print("\t", k, v)
end
end
end
function node_function(node)
end
function Set(list)
local set = {}
for _, l in ipairs(list) do set[l] = true end
return set
end
local function is_in (val, tab)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function SetBrunnelAttributes(obj)
if obj:Find("bridge") == "yes" then obj:Attribute("brunnel", "bridge")
elseif obj:Find("tunnel") == "yes" then obj:Attribute("brunnel", "tunnel")
elseif obj:Find("ford") == "yes" then obj:Attribute("brunnel", "ford")
end
end
linkValues = Set { "motorway_link", "trunk_link", "primary_link", "secondary_link", "tertiary_link" }
-- https://stackoverflow.com/a/7615129/4288232
function split(inputstr, sep)
if sep == nil then
sep = "%s"
end
local t={} ; i=1
for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
t[i] = str
i = i + 1
end
return t
end
function way_function(way)
if way:Find("disused") == "yes" then return end
local name = way:Find("name");
-- highway
local highway = way:Find("highway")
if highway ~= nil and highway ~= "" then
if highway == "proposed" then return end
if G_COUNTS["highway"] == nil then G_COUNTS["highway"] = {} end
if G_COUNTS["highway"][highway] == nil then G_COUNTS["highway"][highway] = 0 end
G_COUNTS["highway"][highway] = G_COUNTS["highway"][highway] + 1
local road_type = "unknown"
local road_min_zoom = 0;
if is_in( highway, { "motorway", "trunk", "primary" } ) then
road_type = "road_main"
end
if is_in( highway, { "motorway_link", "trunk_link", "primary_link", "secondary", "secondary_link" } ) then
road_type = "road_secondary"
road_min_zoom = 6
end
if is_in( highway, { "tertiary", "tertiary_link", "unclassified" } )
then
road_type = "road_tertiary"
road_min_zoom = 10
end
if is_in( highway, { "track", "road", "living_street", "residential", "footway" } )
then
road_type = "other"
road_min_zoom = 14
end
if road_type == "unknown" then
return
end
way:Layer("roads", false)
way:Attribute("class", highway)
-- way:Attribute("class", road_type)
if name ~= nil and name ~= "" then way:Attribute("name",name) end
if road_min_zoom then way:MinZoom(road_min_zoom) end
SetBrunnelAttributes(way)
-- Links (ramp)
if linkValues[highway] then
splitHighway = split(highway, "_")
highway = splitHighway[1]
way:AttributeNumeric("ramp",1)
end
end
-- railway
local railway = way:Find("railway")
if railway ~= nil and railway == "rail" then
if G_COUNTS["railway"] == nil then G_COUNTS["railway"] = {} end
if G_COUNTS["railway"][railway] == nil then G_COUNTS["railway"][railway] = 0 end
G_COUNTS["railway"][railway] = G_COUNTS["railway"][railway] + 1
local layer = "railways"
way:Layer(layer, false)
way:Attribute("class", railway)
if name ~= nil and name ~= "" then
way:Attribute("name",name)
end
end
end

Wyświetl plik

@ -0,0 +1,39 @@
{
"layers": {
"river": {
"minzoom": 5,
"maxzoom": 14,
"simplify_below": 11,
"simplify_level": 0.0015,
"simplify_ratio": 2
},
"water": {
"minzoom": 5,
"maxzoom": 14,
"simplify_below": 13,
"simplify_length": 10,
"simplify_ratio": 3
}
},
"settings": {
"minzoom": 5,
"maxzoom": 14,
"basezoom": 16,
"include_ids": false,
"name": "HAB",
"version": "1.0",
"description": "HAB",
"compress": "none",
"metadata": {
"json": {
"vector_layers": [
{
"id": "water",
"description": "water",
"fields": {}
}
]
}
}
}
}

Wyświetl plik

@ -0,0 +1,108 @@
node_keys = {}
G_DEFAULT = 0
G_COUNTS = {}
function zoom_tile_area(latitude_degrees, zoom_level)
earth_equatorial_circumference = 40075016.686 -- meters
latitude_radians = 3.14159265359 * latitude_degrees / 180.0
tile_width = earth_equatorial_circumference * math.cos(latitude_radians) / (2^zoom_level)
return tile_width*tile_width
end
-- store m2 area for one tile on each zoom level
ZOOM_TILES_AREA = {}
function init_function()
for i=1,16 do
ZOOM_TILES_AREA[i] = zoom_tile_area(52.0, i)
print(ZOOM_TILES_AREA[i])
end
end
local function is_in (val, tab)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function get_min_zoom(in_area)
local min_zoom = 1
for _z=15,1,-1 do
if in_area < (0.01 * ZOOM_TILES_AREA[_z]) then
return _z
end
end
return min_zoom
end
function exit_function()
for _k,_v in pairs(G_COUNTS)
do
print("\n")
print(_k)
for k,v in pairs(_v)
do
print("\t", k, v)
end
end
end
function node_function(node)
end
function way_function(way)
local name = way:Find("name");
-- Water
local natural = way:Find("natural")
if natural ~= nil and natural ~= "" and way:IsClosed() ~= false then
if G_COUNTS["natural"] == nil then G_COUNTS["natural"] = {} end
if G_COUNTS["natural"][natural] == nil then G_COUNTS["natural"][natural] = 0 end
G_COUNTS["natural"][natural] = G_COUNTS["natural"][natural] + 1
if is_in( natural, { "water", "wetland", "bay", "mud" } ) then
local layer = "water"
if layer ~= "" then
way:Layer(layer, way:IsClosed())
way:Attribute("class", natural)
way:MinZoom( get_min_zoom(way:Area()) )
if name ~= nil and name ~= "" then way:Attribute("name",name) end
end
end
end
-- waterway
local waterway = way:Find("waterway")
if waterway ~= nil and waterway ~= "" then
if G_COUNTS["waterway"] == nil then G_COUNTS["waterway"] = {} end
if G_COUNTS["waterway"][waterway] == nil then G_COUNTS["waterway"][waterway] = 0 end
G_COUNTS["waterway"][waterway] = G_COUNTS["waterway"][waterway] + 1
-- if is_in( class, { "yes", "water", "river", "riverbank", "stream", "reservoir", "moat", "pond", "canal" } )
if is_in( waterway, { "yes", "water", "riverbank", "reservoir", "moat", "pond", "canal" } ) then
layer = "water"
way:Layer(layer, way:IsClosed())
way:Attribute("class", waterway)
-- way:MinZoom( get_min_zoom(way:Area()) )
if name ~= nil and name ~= "" then way:Attribute("name",name) end
elseif is_in( waterway, { "river", "stream", "canal" } ) then
layer = "river"
way:Layer(layer, way:IsClosed())
way:Attribute("class", waterway)
-- way:MinZoom( get_min_zoom(way:Area()) )
if name ~= nil and name ~= "" then way:Attribute("name",name) end
end
end
end

Wyświetl plik

@ -0,0 +1,15 @@
#!/bin/sh
##
# $1 is path to PBF file
# $2 is output dir
# /usr/bin/time -v is used to report execution time and memory usage
mkdir $2
/usr/bin/time -v ./tilemaker $1 --output $2/aeroway --config ./hab_aeroway.json --process ./hab_aeroway.lua
/usr/bin/time -v ./tilemaker $1 --output $2/buildings --config ./hab_buildings.json --process ./hab_buildings.lua
/usr/bin/time -v ./tilemaker $1 --output $2/landuse --config ./hab_landuse.json --process ./hab_landuse.lua
/usr/bin/time -v ./tilemaker $1 --output $2/roads --config ./hab_roads.json --process ./hab_roads.lua
/usr/bin/time -v ./tilemaker $1 --output $2/water --config ./hab_water.json --process ./hab_water.lua
/usr/bin/time -v ./tilemaker $1 --output $2/labels --config ./hab_labels.json --process ./hab_labels.lua
/usr/bin/time -v ./tilemaker $1 --output $2/admin --config ./hab_admin.json --process ./hab_admin.lua

148
webUI/README.md 100644
Wyświetl plik

@ -0,0 +1,148 @@
# webUI
![HabBoy](../docs/HabBoy_Habdec.jpg)
```webUI``` is a HabBoy GUI in a web browser:
* connects to ```data_server``` for payload telemetry
* displays any nuber HabDec interfaces
* displays OSM map with payload and HabBoy location
* displays google map with navigation route
* displays graphs and gauges with telemetry using [highcharts.js](https://www.highcharts.com/)
* Displays Habitat SSDV
# Installation
```webUI``` should be server with any web server, ie. apache.
Opening ```index.html``` directly from disk might not work due to CORS restrictions.
For testing, you can start simple python server:
```
cd webUI/code
python -m http.server 80
```
Then open browser and go to http://localhost
For example, if you use apache:
```ln -s ~/habboy/webUI/code /var/www/html/habboy```
Web UI is then available under URL ```http://habboy/habboy```
# User Interface
User Interface is divided in two parts. At the bottom is ```status bar```.
Rest of the UI area is many tabs(Habdec, maps, etc.) that can be switched with buttons at right side of screen.
## Status Bar
```status bar``` is located at the bottom of the screen.
First line displays payload information:
* callsign
* altitude [max altitude]
* ascent rate m/s
* horizontal speed km/h
* GPS fix age (time since last GPS fix)
* last payload sentence age
Color of the payload line has meaning:
* green - 0-60 seconds age
* orange - 60-120 seconds age
* red - more than 120 seconds age
Second line displays information about HabBoy device:
* distance to payload
* payload elevation
* azimuth to payload
* HabBoy vehuicle speed km/h
* GPS fix age
* GPS packet age
## Tabs
Right side of screen is a column of buttons. Each button is a tab.
Custom tabs can be added by editing ```HABBOY.js``` file.
## Tab - HabDec
HabBoy can display multiple HabDec interfaces, one per radio/connection.
Each instance will have it's own TAB named ```Radio XXX```, where XXX is last octed of HabDec IP address.
To install HabDec into HabBoy, create symlink (or copy):
```
cd ./habboy_sw/webUI
ln -s ~/habdec/code/webClient ./habdec_gui
```
To add new habBoy TAB, open URL:
```http://habboy:8888/habboy/api/v1/habdec/add/192.168.1.100:5555```
Where 192.168.1.100:5555 is addr:port oh running habdec websocketServer.
## Tab - Map
```Tab Map``` is OpenStreetMap vetor tiles map with location of payload, HabBoy device and predicted land spot.
To work correctly you must:
* install cusf and wind data as described in [data_server](../data_server/README.md)
* prepare and install vector tiles as described [here](../docs/VECTOR_TILES.md)
## Tab - Google Maps
To enable, edit ```webUI\code\js\HB_google_map.js``` file and fill your google API key in ```GMAPS_API_KEY``` variable.
You can uncomment ```HG_GoogleMap_NavigationUpdate()``` function call to enable google navigation. This needs more work however and is a mere experiment now.
## Tab - Control
Various HabBoy settings.
### Nav
Copy payload lat,lon to clipboard
### Chase Car
Upload HabBoy GPS position to Habitat (as chasecar)
### Payloads...
Select payload to track. These are payloads saved in ```data_server``` DB.
### Device -> habdec_start / habdec_stop
start/stop HabDec daemon
### Device -> spy_start / spy_stop
start/stop SpyServer daemon
### Device -> restart
restart all daemons (habboy and habdec)
### Device -> reboot
reboot computer
### Device -> halt
stop computer
## Directory Structure
Below is a dir structure of ```/var/www/html```
```
~ www tree -d -l -L 4 .
.
└── html
├── habboy -> /home/pi/share/dev/habboy/habboy_sw/webUI/code
│   ├── css
│   ├── habdec_gui -> /home/pi/share/dev/habdec/habdec/code/webClient
│   │   ├── css
│   │   └── js
│   ├── img
│   └── js
│   └── highcharts
├── osm
│   ├── font -> /home/pi/share/data/osm/font/klokantech/font
│   │   ├── Klokantech Noto Sans Bold
│   │   ├── ...
│   │   └── Roboto Thin-Italic
│   └── tiles -> /home/pi/share/data/osm/poland_layered/3
│   ├── admin
│   ├── aeroway
│   ├── buildings
│   ├── labels
│   ├── landuse
│   ├── roads
│   └── water
└── ssdv
└── gallery
```

Wyświetl plik

@ -0,0 +1,110 @@
body, html {
width: 100%;
/* height: 90vh; */
margin: 0;
padding: 0;
font-family: 'Open Sans', sans-serif;
background-color: #000;
}
.HABBOY_MAIN_DIV {
/* height: 100%; */
}
/* single TAB container */
.HB_TAB_DIV {
display: flex;
width: 100%;
height: 100%;
}
/* dov created in tab builder functions */
.HB_TAB_CONTENT_DIV {
display: flex;
width: 100%;
height: 100%;
}
/* bottom */
.HB_STATUS_BAR_DIV {
/* display: flex; */
background-color: var(--HB_tab_button);
color: var(--HB_text);
}
/* top TABS buttons */
.HB_TAB_BUTTON {
background-color: var(--HB_tab_button);
color: var(--HB_text);
margin: 1px;
border: solid;
border-color: var(--HB_tab_button_border);
border-radius: 10px;
cursor: pointer;
font-size: 22px;
}
button {
flex: auto;
background-color: var(--HB_button);
color: var(--HB_text);
border: solid;
border-color: var(--HB_button_border);
border-radius: 10px;
cursor: pointer;
font-size: 22px;
}
img {
width: 100%;
object-fit: contain;
}
.HB_modal_submenu_bg {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
/* overflow: auto; */
/* z-index: 1; */
background-color: var(--HB_bg);
}
.HB_modal_submenu_div {
position: fixed;
left: 10%;
top: 10%;
width: 80%;
height: 80%;
}
table, th, td {
border: 1px solid var(--HB_button_border);
border-collapse: collapse;
/* width: 70%; */
margin-left: auto;
margin-right: auto;
}
p {
color: var(--HB_text);
text-align: center;
margin: 5px;
font-size: 20px;
}
th > p, td > p {
color: var(--HB_text);
text-align: center;
margin: 5px;
font-size: 25px;
}

Wyświetl plik

@ -0,0 +1,20 @@
:root {
--HB_bg: hsl(210, 15%, 14%);
--HB_text: #eee;
--HB_text_highlight: hsl(32, 93%, 45%);
--HB_tab_button:rgb(31, 62, 93);
--HB_tab_button_active:#bb0;
--HB_tab_button_text:#eee;
--HB_tab_button_active_text:#000;
--HB_tab_button_border:rgb(31, 62, 93);
--HB_tab_button_border_highlight:#b80;
--HB_button:rgb(31, 62, 93);
--HB_button_active:#990;
--HB_button_text:#ccc;
--HB_button_active_text:#000;
--HB_button_border:#000;
}

File diff suppressed because one or more lines are too long

Wyświetl plik

@ -0,0 +1,5 @@
#!/usr/bin/python
import sys
print(sys.argv)

Some files were not shown because too many files have changed in this diff Show More