pull/6/head
Michal Fratczak 2018-11-02 16:06:08 +01:00
commit 1a90ed76f3
55 zmienionych plików z 9616 dodań i 0 usunięć

Wyświetl plik

@ -0,0 +1,117 @@
# Building HABDEC from source
To build habdec from source code, you need to build it's dependecies first:
- FFTW
- boost 1.68
- CMake version 3.8.2
- optionally: FLTK
Below are instructions how to obtain and compile each package. Keep in mind, these are WIP and some adjustment to your build env may be needed.
For windows, you need to start 64bit build env, ie: `C:\Program Files (x86)\Microsoft Visual Studio\2017\Community\VC\Auxiliary\Build\vcvars64.bat`
## CMake
#### Windows
Just download and install binaries from https://cmake.org/download/
#### Linux
wget https://cmake.org/files/v3.12/cmake-3.12.3.tar.gz
tar -xf ./cmake-3.12.3.tar.gz
cd cmake-3.12.3
./configure --prefix=`pwd`/install
make -j4
sudo make install
export PATH=$PATH:`pwd`/install
## boost 1.68
#### Linux
wget https://dl.bintray.com/boostorg/release/1.68.0/source/boost_1_68_0.tar.gz
tar -xf ./boost_1_68_0.tar.gz
cd boost_1_68_0
./bootstrap.sh
./b2 -j 4 --layout=tagged --build-type=complete stage
#### Windows
Download from https://www.boost.org/users/download/ and unpack.
cd boost
bootstrap.bat
b2.exe --layout=tagged --build-type=complete --build-dir=build/static toolset=msvc address-model=64 link=static stage
## FFTW
You need to build FFTW with float (single precission) support. Also, enable neon optimizations for ARM.
#### Linux x86
wget http://fftw.org/fftw-3.3.8.tar.gz
tar -xf ./fftw-3.3.8.tar.gz
cd fftw-3.3.8
./configure --with-slow-timer --enable-single CFLAGS="-O4 -pipe -march=native -Wall" --prefix=`pwd`/install
make
make install
#### Linux ARM
wget http://fftw.org/fftw-3.3.8.tar.gz
tar -xf ./fftw-3.3.8.tar.gz
cd fftw-3.3.8
./configure --with-slow-timer --enable-single --enable-neon CFLAGS="-O4 -pipe -march=native -mfpu=neon -Wall" --prefix=`pwd`/install
make
make install
#### Windows
Download http://fftw.org/fftw-3.3.8.tar.gz and unpack.
cmake -D BUILD_SHARED_LIBS=0 -D ENABLE_FLOAT=1 -D CMAKE_INSTALL_PREFIX=d:\dev\c_libs\fftw\3.3.8\install -D CMAKE_BUILD_TYPE=RELEASE -G "NMake Makefiles" ..\src
nmake
nmake install
## SoapySDR
#### Windows
Just go and install binaries from https://github.com/pothosware/PothosCore/wiki/Downloads
#### Linux
git clone https://github.com/pothosware/SoapySDR.git
cd SoapySDR
git pull origin master
mkdir build
cd build
cmake ..
make -j
sudo make install
sudo ldconfig
SoapySDRUtil --info
### SoapySDR AirSpy Support
git clone https://github.com/pothosware/SoapyAirspy.git
mkdir build
cd build
cmake ../SoapySDR
make
sudo make install
sudo ldconfig
### SoapySDR RTL-SDR Support
Refer to https://github.com/pothosware/SoapyRTLSDR
## HABDEC Build
If you managed to build or install dependencies, you're ready do build habdec
git clone habdec
cd habdec
mkdir build
cd build
cmake cmake -D BOOST_ROOT=/path/to/boost_1.68 -D FFTW_ROOT=/path/to/fftwf/install ../code
make
make install
You should end up with `install` dir that contains executable and a shell script that runs in loop (for cases where habdec should crash and you wan't continous run).

674
COPYING 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>.

175
README.md 100644
Wyświetl plik

@ -0,0 +1,175 @@
# HABDEC - RTTY decoder for High Altitude Balloons
![alt text](./webClientScreenshot.png)
Habdec is a C++11 software to decode RTTY telemetry from High Altitude Balloon and upload it to [UKHAS Habitat](http://habitat.habhub.org/)
Some facts:
- builds and runs on Windows/Linux and x64/RaspberryPI/OdroixXU4 platforms
- Uses [SoapySDR](https://github.com/pothosware/SoapySDR) to consume IQ stream from your SDR
- runs in command line (headless)
- provides websocket server so can be cotrolled from any web browser [even on your phone](https://www.youtube.com/watch?v=dli8FEFy5tM)
- can be easily integrated into your own code
Original motivation for habdec was to have a portable tracking device you could take to a chasecar or into a field.
Fatty laptop with dl-fldigi, full-fledged SDR app and required internet connection is not too comfortable.
Ultimatelly habdec is intended for integration into bigger app, probably based on OpenStreetmap and running on portable RaspberryPI or OdroidXU4. Right now you can run it on headless board and cotrol from your mobile.
## Getting habdec
To get habdec you can download precompiled exec or build it from source.
#### Getting Binary:
- Install SoapySDR binaries from [here](https://github.com/pothosware/SoapySDR/wiki#installation)
- Download habdec executable for your platform from [here](missing link)
#### Building from source:
To build habdec you need a C++11 compiler and CMake version 3.8.2
You also need to build or install some dependencies:
- basic decoder: [FFTW](http://www.fftw.org/)
- websocket server: [SoapySDR](https://github.com/pothosware/SoapySDR), [boost 1.68](https://www.boost.org/)
Instructions how to build habdec and it's dependencies are described in [BuildInstructions.md](./BuildInstructions.md)
## Usage
`habdecWebsocketServer.exe --help`
```
Command Line Interface options:
--config arg (=./habdecWebsocketServer.opts)
Last run config file. Autosaved on
every successfull decode.
CLI opts:
--help Display help message
--device arg (=-1) SDR Device Numer
--sampling_rate arg (=0) Sampling Rate, as supported by device
--port arg (=5555) Command Port, example: --port
127.0.0.1:5555
--station arg (=habdec) HABHUB station callsign
--freq arg frequency in MHz
--gain arg gain
--print arg live print received chars
--rtty arg rtty: baud bits stops, example -rtty
300 8 2
--biast arg biasT
--bias_t arg biasT
--afc arg Auto Frequency Correction
```
The only mandatory parameter is --sampling_rate. Provide value that is supported by your SDR device.
### Examples:
Print available devices
```
habdecWebsocketServer.exe --device -1
Reading config from file ./habdecWebsocketServer.opts
Current options:
device: -1
sampling_rate: 2.048e+06
command_host: 0.0.0.0
command_port: 5,555
station: habdec
freq: 4.3435e+08
gain: 15
live_print: 1
baud: 300
rtty_ascii_bits: 8
rtty_ascii_stops: 2
biast: 0
ERROR: Unable to find host: Nieznany host.
Found Rafael Micro R820T tuner
[INFO] [UHD] Win32; Microsoft Visual C++ version 14.0; Boost_106700; UHD_3.13.0.2-1-g78745bda
Available devices:
0:
device_id 0
driver airspy
label AIRSPY [440464c8:39627b4f]
serial 440464c8:39627b4f
Sampling Rates:
2.5e+06
1e+07
1:
available Yes
driver rtlsdr
label Generic RTL2832U OEM :: 00000001
manufacturer Realtek
product RTL2838UHIDIR
rtl 0
serial 00000001
tuner Rafael Micro R820T
Found Rafael Micro R820T tuner
Sampling Rates:
250,000
1.024e+06
1.536e+06
1.792e+06
1.92e+06
2.048e+06
2.16e+06
2.56e+06
2.88e+06
3.2e+06
No SDR device specified. Select one by specifying it's NUMBER
Failed Device Setup. EXIT.
```
Run with AirSpy
habdecWebsocketServer.exe --device 0 --sampling_rate 2.5e6
Specify websocket address and port
habdecWebsocketServer.exe --device 0 --sampling_rate 2.5e6 -port 12.13.14.15:5555
Some more options
```
habdecWebsocketServer.exe --device 0 --sampling_rate 2.5e6
--port 12.13.14.15:5555 --station Fred
--rtty 300 8 2
--print 1
--freq 434.5 --gain 20 --biast 1 --afc 1
```
### Web Client
To control habdec parameters from your browser, start `webClient/index.html` and connect to ip:port
## Known Limitations
- RTTY Modes **NOT** supported: 5bit baudot, 1.5 bit stop
- SSTV is not supported
- Decoding will stop if decimation setting is too low or too high. It was tested to work with stream around 40kHz bandwidth.
- Automatic Frequency Correction needs more work. Use consciously.
- Connecting from browser is not very reliable yet, sometimes you need to refresh and wait.
- Currently, upload to HABHUB is realized with python habLogger.py which is called with system(). This will get ported to C++.
- habdec was developed and tested with [AirSpy](https://airspy.com/) and [OdroidXU4](http://hardkernel.com/). Support for windows and RtlSdr is less tested.
## Reporting Problems
Use bugtracker, please.
## Contributions
Gladly accepted :)
## Authors
* **Michał Frątczak** - *parts of code from* - [GQRX](https://github.com/csete/gqrx)
## License
This project is licensed under the GNU General Public License

Wyświetl plik

@ -0,0 +1,17 @@
# defined since 2.8.3
if (CMAKE_VERSION VERSION_LESS 2.8.3)
get_filename_component (CMAKE_CURRENT_LIST_DIR ${CMAKE_CURRENT_LIST_FILE} PATH)
endif ()
# Allows loading FFTW3 settings from another project
set (FFTW3_CONFIG_FILE "${CMAKE_CURRENT_LIST_FILE}")
# set (FFTW3f_LIBRARIES fftw3f.a )
FIND_LIBRARY( FFTW3f_LIBRARIES NAMES fftw3f.a fftw3f PATHS ${FFTW_ROOT}/lib NO_DEFAULT_PATH )
set (FFTW3f_LIBRARY_DIRS ${FFTW_ROOT}/lib)
set (FFTW3f_INCLUDE_DIRS ${FFTW_ROOT}/include)
if (CMAKE_VERSION VERSION_LESS 2.8.3)
set (CMAKE_CURRENT_LIST_DIR)
endif ()

Wyświetl plik

@ -0,0 +1,12 @@
set (PACKAGE_VERSION "3.3.7")
# Check whether the requested PACKAGE_FIND_VERSION is compatible
if ("${PACKAGE_VERSION}" VERSION_LESS "${PACKAGE_FIND_VERSION}")
set (PACKAGE_VERSION_COMPATIBLE FALSE)
else ()
set (PACKAGE_VERSION_COMPATIBLE TRUE)
if ("${PACKAGE_VERSION}" VERSION_EQUAL "${PACKAGE_FIND_VERSION}")
set (PACKAGE_VERSION_EXACT TRUE)
endif ()
endif ()

Wyświetl plik

@ -0,0 +1,25 @@
cmake_minimum_required( VERSION 3.8.2 )
project (habdec)
set ( CMAKE_CXX_STANDARD 11 )
# 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} )
add_subdirectory("Decoder")
add_subdirectory("IQSource")
add_subdirectory("websocketServer")
option( fltkGUI "fltkGUI" OFF )
if(fltkGUI)
add_subdirectory("fltkGUI")
endif()

385
code/Decoder/AFC.h 100644
Wyświetl plik

@ -0,0 +1,385 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <vector>
#include <complex>
#include <numeric>
#include <iostream>
#include "IQVector.h"
#include "Average.h"
namespace
{
template<typename TIQVector, typename TRVector>
bool FftPower(const TIQVector& fft_samples, TRVector& o_power_arr);
template<typename VEC>
double ComputeVariance(const VEC& i_containter, const double mean);
template<typename TRVector>
void FindPeaks( const TRVector& v,
const double expected_relative_separation,
int* p_peak1, int* p_peak2 );
}
namespace habdec
{
template<typename TReal>
class AFC
{
public:
typedef std::complex<TReal> TComplex;
typedef std::vector<TReal> TRVector;
typedef habdec::IQVector<TReal> TIQVector;
AFC() = default;
void setFftSamples(const TIQVector& i_fft_samples) { fft_samples_ = i_fft_samples; }
double process();
double operator()() { return process(); }
const TRVector& getPowerSpectrum() const { return power_arr_; }
double getFrequencyCorrection() const { return frequency_correction_; }
void resetFrequencyCorrection(const double frequency_correction);
double getShift() const { return shift_Hz_; }
void getPeaks(int& pl, int& pr) const { pl = gui_peak_left_; pr = gui_peak_right_; }
void getNoiseFloor(double& nf, double& nv) const { nf = noise_floor_; nv = noise_variance_; }
private:
TIQVector fft_samples_; // input FFT samples
TRVector power_arr_;
double frequency_correction_ = 0;
double noise_floor_ = 0;
double noise_variance_ = 0;
habdec::Average<double> noise_floor_avg_ {100};
habdec::Average<double> noise_variance_avg_ {100};
habdec::Average<int> peak_left_avg_ {4};
habdec::Average<int> peak_right_avg_ {4};
double shift_Hz_ = 0; // peak separation in Hz
int gui_peak_left_ = 0;
int gui_peak_right_ = 0;
};
template<typename TReal>
double AFC<TReal>::process()
{
using namespace std;
bool b_debug = 0;
if(b_debug)
cout<<"AFC::process begin"<<endl;
// if(fft_samples_.size() != 4096)
if(0)
{
fft_samples_.clear();
frequency_correction_ = 0;
if(b_debug)
cout<<"AFC::process fft_samples_.size() != 1024 exit "<<fft_samples_.size()<<endl;
return 0;
}
if(b_debug)
cout<<"AFC::process FftPower..."<<endl;
if( !FftPower(fft_samples_, power_arr_) )
{
// fft_samples_.clear();
frequency_correction_ = 0;
if(b_debug)
cout<<"AFC::process !FftPower. exit."<<endl;
return 0;
}
// noise floor
noise_floor_ = double(accumulate(power_arr_.begin(), power_arr_.end(), 0.0)) / power_arr_.size();
noise_variance_ = ComputeVariance(power_arr_, noise_floor_);
noise_floor_avg_.add( noise_floor_ );
noise_variance_avg_.add( noise_variance_ );
if(b_debug)
cout<<"AFC::process noise_floor_avg_:"<<noise_floor_avg_<<" noise_variance_avg_:"<<noise_variance_avg_<<endl;
// expected separation between peaks
// const float fsk_shift = ( 0 < shift_Hz_ && shift_Hz_ < 2000 ) ? shift_Hz_ : 500; //Hz
const float fsk_shift = 500;
float expected_relative_separation = fsk_shift/fft_samples_.samplingRate(); // 500 Hz in 39kHz span
// two maximum peaks
int p1, p2;
FindPeaks(power_arr_, expected_relative_separation, &p1, &p2);
if(b_debug)
cout<<"AFC::process peaks: "<<p1<<" "<<p2<<endl;
// it cannot be resolved which is left/right
// unless both are present (stronger than peak_detect_threshold)
const float peak_detect_threshold = noise_floor_avg_ + 3 * fabs(noise_variance_avg_);
bool b_p1_detected = false;
if( power_arr_[p1] > peak_detect_threshold ) // peak detected
b_p1_detected = true;
bool b_p2_detected = false;
if( power_arr_[p2] > peak_detect_threshold ) // peak detected
b_p2_detected = true;
// peaks position stability
const int peak_stability_threshold = 2; // expressed in bins
bool b_peak_left_stable = false;
bool b_peak_right_stable = false;
if(b_p1_detected && b_p2_detected)
{
if(p2<p1)
swap(p1, p2);
if( peak_left_avg_.add(p1) <= peak_stability_threshold ) // peak stable
b_peak_left_stable = true;
if( peak_right_avg_.add(p2) <= peak_stability_threshold ) // peak stable
b_peak_right_stable = true;
}
// peaks gui display
// unstable peaks are drawn with dimmer color (nagative sign)
gui_peak_left_ = 0;
if(b_p1_detected)
{
if(b_peak_left_stable)
gui_peak_left_ = peak_left_avg_;
else
gui_peak_left_ = - peak_left_avg_; // not valid
}
gui_peak_right_ = 0;
if(b_p2_detected)
{
if(b_peak_right_stable)
gui_peak_right_ = peak_right_avg_;
else
gui_peak_right_ = - peak_right_avg_; // not valid
}
// correct frequency only if both peaks stable
if(b_peak_left_stable && b_peak_right_stable)
{
const int peak_left = round( (double) peak_left_avg_ );
const int peak_right = round( (double) peak_right_avg_ );
const int bins_dist = peak_right - peak_left;
const double Hertz_per_bin = fft_samples_.samplingRate() / fft_samples_.size();
shift_Hz_ = Hertz_per_bin * bins_dist;
const double middle_peak = peak_left + bins_dist / 2;
const double bins_error = middle_peak - double(fft_samples_.size()) / 2;
const double freq_error = Hertz_per_bin * bins_error;
const int bin_dist_threshold = 4;
if( bin_dist_threshold < abs(bins_error) )
frequency_correction_ = freq_error;
}
return frequency_correction_;
}
template<typename TReal>
void AFC<TReal>::resetFrequencyCorrection(const double frequency_correction)
{
const double bins_per_Hertz = (double)fft_samples_.size() / fft_samples_.samplingRate();
peak_left_avg_.reset( std::max((double) 0, peak_left_avg_ - frequency_correction * bins_per_Hertz) );
peak_right_avg_.reset(std::max((double) 0, peak_right_avg_ - frequency_correction * bins_per_Hertz) );
frequency_correction_ = 0;
}
} // namespace habdec
namespace
{
template<typename TReal>
bool hasNan(const TReal* v, size_t sz)
{
for(size_t i=0; i<sz; ++i)
if(v[i] != v[i])
return true;
return false;
}
template<typename TReal>
bool hasInf(const TReal* v, size_t sz)
{
for(size_t i=0; i<sz; ++i)
if(std::isinf(v[i]))
return true;
return false;
}
template<typename VEC>
double ComputeVariance(const VEC& i_containter, const double mean)
{
double var = 0;
for(const auto& v : i_containter )
var += (v - mean) * (v - mean);
var /= i_containter.size();
return sqrt(var);
}
template<typename TIQVector, typename TRVector>
bool FftPower(const TIQVector& fft_samples, TRVector& o_power_arr)
{
// http://nl.mathworks.com/help/signal/ug/power-spectral-density-estimates-using-fft.html
using namespace std;
bool b_debug = 0;
if(!fft_samples.size())
return 0;
if(!fft_samples.samplingRate())
return 0;
if(0)
{
size_t i=0;
for(auto c : fft_samples)
cout<<i++<<" "<<c<<"\n";
cout<<endl;
}
auto* p_fft_samples_data = const_cast<typename TIQVector::TComplex*>(fft_samples.data());
if(b_debug)
cout<<"FftPower NaN"<<endl;
if( hasNan(reinterpret_cast<typename TIQVector::TValue*>(p_fft_samples_data), fft_samples.size()*2) )
{
cout<<"FftSpectrum Nan"<<endl;
return 0;
}
if(b_debug)
cout<<"FftPower Inf"<<endl;
if( hasInf(reinterpret_cast<typename TIQVector::TValue*>(p_fft_samples_data), fft_samples.size()*2) )
{
cout<<"FftSpectrum Inf"<<endl;
return 0;
}
o_power_arr.resize(fft_samples.size());
if(b_debug)
cout<<"FftPower o_power_arr.size() "<<o_power_arr.size()<<endl;
if(b_debug)
cout<<"FftPower compute... "<<endl;
for(size_t i=0; i<fft_samples.size(); ++i)
{
o_power_arr[i] = norm(fft_samples[i]) / fft_samples.size(); // normalize by N
o_power_arr[i] = o_power_arr[i] * o_power_arr[i];
o_power_arr[i] /= fft_samples.samplingRate();
o_power_arr[i] = 10.0f * log10( o_power_arr[i] );
}
if(b_debug)
cout<<"FftPower post NaN"<<endl;
if( hasNan(o_power_arr.data(), o_power_arr.size()) )
{
cout<<"Power Nan"<<endl;
return 0;
}
if(b_debug)
cout<<"FftPower post inf"<<endl;
if( hasInf(o_power_arr.data(), o_power_arr.size()) )
{
cout<<"Power Inf"<<endl;
return 0;
}
if(b_debug)
cout<<"FftPower DONE."<<endl;
return 1;
}
template<typename TRVector>
void FindPeaks( const TRVector& v,
const double expected_relative_separation,
int* p_peak1, int* p_peak2 )
{
using namespace std;
// FIND TWO MAXIMUMS SEPARATED AT LEAST BY BINS_SEP
//
int bins_sep = round(expected_relative_separation * v.size());
bins_sep = std::max(8, bins_sep);
// first peak
auto i_max = max_element(v.begin(), v.end());
int p1 = i_max - v.begin();
float p1_val = *i_max;
// second peak
int begin = std::max( p1 - 2 * bins_sep, 0 );
int end = std::min( p1 + 2 * bins_sep, (int) v.size() );
int p2 = 0;
float p2_val = v[0];
for(int i=begin; i<end; ++i)
{
if(v[i] > p2_val && abs(i-p1) > bins_sep/2)
{
p2 = i;
p2_val = v[i];
}
}
if(p2<p1)
{
swap(p1, p2);
swap(p1_val, p2_val);
}
*p_peak1 = p1;
*p_peak2 = p2;
}
} // namespace

Wyświetl plik

@ -0,0 +1,80 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <memory>
#include <iostream>
namespace habdec
{
template<typename T>
class Average
{
public:
Average(size_t max_count, T init_val=0) : sum_(0), count_(0), max_count_(std::max(size_t(1),max_count))
{
add(init_val);
};
double add(const T& val)
{
double diff = get() - val;
if(count_ == max_count_)
{
sum_ = get() * (max_count_-1) + val;
}
else
{
++count_;
sum_ += val;
}
return diff;
}
double get() const
{
if(!count_)
return sum_;
return double(sum_)/count_;
}
operator double() const { double val = get(); return val; }
void reset(const T& val)
{
sum_ = val;
count_ = 1;
}
private:
T sum_;
size_t count_;
const size_t max_count_;
};
} // namespace habdec

Wyświetl plik

@ -0,0 +1,55 @@
include_directories( ${PROJECT_SOURCE_DIR} )
include_directories( ${CMAKE_CURRENT_SOURCE_DIR} )
set ( FFTW3f_DIR ../CMake )
find_package( FFTW3f REQUIRED )
include_directories( ${FFTW3f_INCLUDE_DIRS} )
message( "FFTW Include:" ${FFTW3f_INCLUDE_DIRS} )
message( "FFTW Lib:" ${FFTW3f_LIBRARIES} )
# RTTY DECODER
set ( Decoder_src
AFC.h
Average.h
${PROJECT_SOURCE_DIR}/common/console_colors.h
${PROJECT_SOURCE_DIR}/common/console_colors.cpp
CRC.h CRC.cpp
Decimator.h
Decoder.h
FFT.h FFT.cpp
filtercoef.h
FirFilter.h
FSK2_Demod.h
func_timer.h
habdec_windows.h
IQVector.h
print_habhub_sentence.h print_habhub_sentence.cpp
RTTY.h
sentence_extract.h sentence_extract.cpp
SpectrumInfo.h
SymbolExtractor.h
)
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" )
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()
add_library( Decoder ${Decoder_src})
target_link_libraries( Decoder
#${SoapySDR_LIBRARIES}
${FFTW3f_LIBRARIES}
${PlatformSpecificLinking} )

Wyświetl plik

@ -0,0 +1,49 @@
#include "CRC.h"
#include <string>
namespace
{
char _hex(char Character)
{
char _hexTable[] = "0123456789ABCDEF";
return _hexTable[int(Character)];
}
}
namespace habdec
{
std::string CRC(std::string i_str)
{
using std::string;
unsigned int CRC = 0xffff;
// unsigned int xPolynomial = 0x1021;
for (size_t i = 0; i < i_str.length(); i++)
{
CRC ^= (((unsigned int)i_str[i]) << 8);
for (int j=0; j<8; j++)
{
if (CRC & 0x8000)
CRC = (CRC << 1) ^ 0x1021;
else
CRC <<= 1;
}
}
string result;
result += _hex((CRC >> 12) & 15);
result += _hex((CRC >> 8) & 15);
result += _hex((CRC >> 4) & 15);
result += _hex(CRC & 15);
return result;
}
} // namespace habdec

10
code/Decoder/CRC.h 100644
Wyświetl plik

@ -0,0 +1,10 @@
#pragma once
#include <string>
namespace habdec
{
std::string CRC(std::string i_str);
} // namespace habdec

Wyświetl plik

@ -0,0 +1,149 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstring>
#include <vector>
#include <complex>
#include <memory>
#include <iostream>
namespace habdec
{
template<typename Ts, typename Tt>
class Decimator
{
public:
Decimator() {};
Decimator(int decimation_factor, const Tt* p_taps, const size_t taps_size);
void setInput(const Ts* p_in, const size_t in_size);
void setOutput(Ts* p_out);
void setFilter(const Tt* p_taps, const size_t taps_size);
size_t operator()();
void setFactor(const int i_f) {decimation_factor_ = i_f;}
int factor() const {return decimation_factor_;}
private:
int decimation_factor_ = 0;
const Ts* p_in_ = 0;
size_t p_in_size_ = 0;
Ts* p_out_ = 0; //size is p_in_size_/decimation_factor_
std::vector<Ts> p_buff_;
std::vector<Tt> p_taps_;
size_t decimated_samples_count_ = 0;
};
template<typename Ts, typename Tt>
Decimator<Ts,Tt>::Decimator(int decimation_factor, const Tt* p_taps, const size_t taps_size)
{
setFactor(decimation_factor);
setFilter(p_taps, taps_size);
}
template<typename Ts, typename Tt>
void Decimator<Ts,Tt>::setInput(const Ts* p_in, const size_t in_size)
{
p_in_ = p_in;
p_in_size_ = in_size;
const size_t new_buff_size = p_in_size_ + p_taps_.size() + decimation_factor_;
if(p_buff_.size() < new_buff_size)
{
p_buff_.resize(new_buff_size);
memset( p_buff_.data(), 0, sizeof(Ts) * p_taps_.size() );
}
}
template<typename Ts, typename Tt>
void Decimator<Ts,Tt>::setFilter(const Tt *p_taps, const size_t taps_size)
{
p_taps_.resize(taps_size);
memcpy( (void*) p_taps_.data(), p_taps, taps_size * sizeof(Tt));
}
template<typename Ts, typename Tt>
void Decimator<Ts,Tt>::setOutput(Ts* p_out)
{
p_out_ = p_out;
}
template<typename Ts, typename Tt>
size_t Decimator<Ts,Tt>::operator()()
{
if(!decimation_factor_ || !p_in_ || !p_out_ || !p_buff_.size())
{
std::cout<<"Decimator not fully initialised"<<std::endl;
return 0;
}
decimated_samples_count_ = 0;
if(!p_buff_.size())
{
std::cout<<"p_buff_ = 0"<<std::endl;
return 0;
}
/*if( !(p_taps_.size()%2) )
{
std::cout<<"taps count not odd "<<p_taps_.size()<<std::endl;
return 0;
}*/
// copy samples to buffer, offseted by taps_count-1
memcpy( p_buff_.data()+p_taps_.size()-1,
p_in_,
p_in_size_ * sizeof(Ts) );
// apply filter
for( size_t in = 0, out=0;
in < p_in_size_ && out < p_in_size_ / decimation_factor_;
in += decimation_factor_, out += 1 // downsampling
)
{
Ts accumulator = 0;
for(size_t t=0; t < p_taps_.size(); ++t)
accumulator += p_buff_[in+t] * p_taps_[t];
p_out_[out] = accumulator;
++decimated_samples_count_;
}
// wrapping. copy last part (p_taps_.size()-1) of (unfiltered) input signal to start of buffer
memcpy( p_buff_.data(),
p_in_ + p_in_size_-p_taps_.size()+1,
(p_taps_.size()-1) * sizeof(Ts) );
return decimated_samples_count_;
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,803 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <iostream>
#include <vector>
#include <complex>
#include <chrono>
#include <mutex>
#include "IQVector.h"
#include "Decimator.h"
#include "FFT.h"
#include "FirFilter.h"
#include "filtercoef.h"
#include "FSK2_Demod.h"
#include "SymbolExtractor.h"
#include "RTTY.h"
#include "sentence_extract.h"
#include "Decoder.h"
#include "AFC.h"
#include "SpectrumInfo.h"
#include "print_habhub_sentence.h"
#include "CRC.h"
namespace habdec
{
template<typename TReal>
class Decoder
{
// STEPS:
//
// multi stage Decimation
// FFT
// Auto Frequency Correct
// FIR Filtering
// Demodulation (Polar Discriminant)
// Symbol Extraction
// RTTY
public:
typedef TReal TValue;
typedef std::complex<TReal> TComplex;
typedef std::vector<TReal> TRVector;
typedef habdec::IQVector<TReal> TIQVector;
typedef habdec::Decimator< std::complex<TReal>, TReal > TDecimator;
typedef habdec::FirFilter< std::complex<TReal>, TReal> TFIR;
// feed decoder
bool pushSamples(const TIQVector& i_stream);
// configure options
void lowpass_bw(float i_lowpass_bw);
float lowpass_bw() const;
void lowpass_trans(float i_lowpass_trans);
float lowpass_trans() const;
void baud(double i_baud);
double baud() const;
void rtty_bits(size_t i_ascii_bits);
size_t rtty_bits() const;
void rtty_stops(float i_ascii_stops);
float rtty_stops() const;
size_t setupDecimationStagesFactor(const size_t i_factor);
size_t setupDecimationStagesBW(const double i_max_sampling_rate);
// get result
std::string getRTTY();
std::string getLastSentence();
// get info
int getDecimationFactor() const;
double getInputSamplingRate() const;
double getDecimatedSamplingRate() const;
double getSymbolRate() const;
// get data for GUI
size_t getBinsCount() const;
const TIQVector getFFT() const;
const TRVector getDemodulated() const;
const TRVector getPowerSpectrum() const;
void getPeaks(int& pl, int& pr);
void getNoiseFloor(double& nf, double& nv);
double getShift() const;
double getFrequencyCorrection() const;
void resetFrequencyCorrection(double frequency_correction);
// template<typename T>
SpectrumInfo<TReal> getSpectrumInfo();
// run it
void process();
void operator()()
{
typedef std::chrono::nanoseconds TDur;
auto _start = std::chrono::high_resolution_clock::now();
process();
TDur _duration = std::chrono::duration_cast<TDur>(std::chrono::high_resolution_clock::now() - _start);
// std::cout<<"process() duration "<<_duration.count()<<" nS "<<double(10e9)/_duration.count()<<"\n";
};
bool livePrint() const { return live_print_; }
void livePrint(bool i_live) { live_print_ = i_live; }
void (*success_callback_)(std::string, std::string, std::string) {0}; // callback on successfull sentence decode
private:
// IQ buffers
TIQVector iq_in_buffer_; // input IQ buffer
mutable std::mutex iq_in_buffer_mtx_;
TIQVector iq_samples_temp_; // temporary processing
TIQVector iq_samples_decimated_; // decimated IQ samples storage
TIQVector iq_samples_filtered_; // FIR filtered IQ samples storage
// init
void init(const float i_sampling_rate); // called on first pushSamples()
// multistage decimation
const double max_decimated_sampling_rate_ = 40e3;
std::vector<TDecimator> decimation_stages_;
int decimation_factor_ = 1;
// FFT
const size_t fft_bins_cnt_ = 1<<12;
FFT fft_; //TODO ! this is only float !
TIQVector freq_in_; // FFT of chunk size
TIQVector freq_out_; // FFT of chunk size
mutable std::mutex freq_out_mtx_;
// AFC
AFC<TReal> afc_;
mutable std::mutex afc_mtx_;
// Low Pass FIR
float lowpass_bw_ = 0.05;
float lowpass_trans_ = 0.0025;
TFIR lowpass_fir_;
mutable std::mutex lowpass_fir_mtx_;
// Demodulation
TRVector demodulated_; // result of Polar Discriminant
mutable std::mutex demodulated_mtx_;
// Symbol Extraction from demodulated samples
SymbolExtractor<TReal> symbol_extractor_;
// RTTY reconstruction from bits
RTTY<bool> rtty_;
std::string rtty_char_stream_; // result of rtty
std::string last_sentence_; // result of rtty
// size_t last_sentence_len_ = 0; // optimization for regexp run
// threading
mutable std::mutex process_mutex_; // mutex for main processing
bool live_print_ = true; // live print decoded characters
};
template<typename TReal>
bool habdec::Decoder<TReal>::pushSamples(const TIQVector& i_stream)
{
{
std::lock_guard<std::mutex> _lock(iq_in_buffer_mtx_);
const size_t pre_insert_size = iq_in_buffer_.size();
iq_in_buffer_.resize( pre_insert_size + i_stream.size() );
memcpy( iq_in_buffer_.data() + pre_insert_size, i_stream.data(), i_stream.size() * sizeof(TComplex) );
}
if( !iq_in_buffer_.samplingRate() )
init( i_stream.samplingRate() );
return true;
}
template<typename TReal>
void habdec::Decoder<TReal>::init(const float i_sampling_rate)
{
iq_in_buffer_.samplingRate(i_sampling_rate);
setupDecimationStagesBW(10.1e6/256);
std::lock_guard<std::mutex> lock(process_mutex_);
// FFT
freq_in_.reserve(fft_bins_cnt_);
freq_out_.reserve(fft_bins_cnt_);
}
template<typename TReal>
void habdec::Decoder<TReal>::lowpass_bw(float i_lowpass_bw)
{
std::lock_guard<std::mutex> _lock(lowpass_fir_mtx_);
lowpass_bw_ = i_lowpass_bw;
lowpass_fir_.LP_BlackmanHarris(lowpass_bw_, lowpass_trans_);
}
template<typename TReal>
float habdec::Decoder<TReal>::lowpass_bw() const
{
return lowpass_bw_;
}
template<typename TReal>
void habdec::Decoder<TReal>::lowpass_trans(float i_lowpass_trans)
{
std::lock_guard<std::mutex> _lock(lowpass_fir_mtx_);
lowpass_trans_ = i_lowpass_trans;
lowpass_fir_.LP_BlackmanHarris(lowpass_bw_, lowpass_trans_);
}
template<typename TReal>
float habdec::Decoder<TReal>::lowpass_trans() const
{
return lowpass_trans_;
}
template<typename TReal>
size_t habdec::Decoder<TReal>::setupDecimationStagesFactor(const size_t i_factor)
{
using namespace std;
if( i_factor<1 || i_factor>256 )
{
cout<<"Unsupported decimation factor: "<<i_factor<<endl;
return getDecimationFactor();
}
if(!iq_in_buffer_.samplingRate())
return 0;
std::lock_guard<std::mutex> lock(process_mutex_);
decimation_stages_.clear();
decimation_factor_ = 1;
switch(i_factor)
{
case 256:
decimation_stages_.emplace_back( TDecimator(64, &d_256_r_64_kernel[0], d_256_r_64_len) );
decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) );
break;
case 128:
decimation_stages_.emplace_back( TDecimator(32, &d_128_r_32_kernel[0], d_128_r_32_len) );
decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) );
break;
case 64:
decimation_stages_.emplace_back( TDecimator(32, &d_64_r_32_kernel[0], d_64_r_32_len) );
decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) );
break;
case 32:
decimation_stages_.emplace_back( TDecimator(16, &d_32_r_16_kernel[0], d_32_r_16_len) );
decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) );
break;
case 16:
decimation_stages_.emplace_back( TDecimator(8, &d_16_r_8_kernel[0], d_16_r_8_len) );
decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) );
break;
case 8:
decimation_stages_.emplace_back( TDecimator(8, &d_8_r_8_kernel[0], d_8_r_8_len) );
break;
case 4:
decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) );
break;
case 2:
decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) );
break;
default:
cout<<"Unsupported decimation factor: "<<i_factor<<endl;
return 0;
}
decimation_factor_ = i_factor;
cout<<"Decoder::setupDecimationStagesFactor Decimation Stages: ";
for(const auto& d : decimation_stages_)
cout<<"/"<<d.factor();
cout<<endl;
cout<<"Decoder::setupDecimationStagesFactor Post Decimation Sampling Rate = "<<getDecimatedSamplingRate()
<<", decimation factor = "<<decimation_factor_<<endl;
return decimation_factor_;
}
template<typename TReal>
size_t habdec::Decoder<TReal>::setupDecimationStagesBW(const double i_max_sampling_rate)
{
using namespace std;
if(!iq_in_buffer_.samplingRate())
return 0;
std::lock_guard<std::mutex> lock(process_mutex_);
double result_sampling_rate = iq_in_buffer_.samplingRate();
decimation_stages_.clear();
decimation_factor_ = 1;
while(result_sampling_rate > i_max_sampling_rate)
{
// available division ratios:
// d_2_r_2
// d_4_r_4
// d_8_r_8
// d_16_r_8
// d_32_r_16
// d_64_r_32
// d_128_r_32
// d_256_r_64
// divide by two until threshold
int div;
for(div=2; div<256; div *= 2)
if( result_sampling_rate/div <= i_max_sampling_rate )
break;
result_sampling_rate /= div;
decimation_factor_ *= div;
switch(div)
{
case 256:
decimation_stages_.emplace_back( TDecimator(64, &d_256_r_64_kernel[0], d_256_r_64_len) );
decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) );
break;
case 128:
decimation_stages_.emplace_back( TDecimator(32, &d_128_r_32_kernel[0], d_128_r_32_len) );
decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) );
break;
case 64:
decimation_stages_.emplace_back( TDecimator(32, &d_64_r_32_kernel[0], d_64_r_32_len) );
decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) );
break;
case 32:
decimation_stages_.emplace_back( TDecimator(16, &d_32_r_16_kernel[0], d_32_r_16_len) );
decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) );
break;
case 16:
decimation_stages_.emplace_back( TDecimator(8, &d_16_r_8_kernel[0], d_16_r_8_len) );
decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) );
break;
case 8:
decimation_stages_.emplace_back( TDecimator(8, &d_8_r_8_kernel[0], d_8_r_8_len) );
break;
case 4:
decimation_stages_.emplace_back( TDecimator(4, &d_4_r_4_kernel[0], d_4_r_4_len) );
break;
case 2:
decimation_stages_.emplace_back( TDecimator(2, &d_2_r_2_kernel[0], d_2_r_2_len) );
break;
}
}
cout<<"Decoder::setupDecimationStagesBW Decimation Stages: ";
for(const auto& d : decimation_stages_)
cout<<"/"<<d.factor();
cout<<endl;
cout<<"Decoder::setupDecimationStagesBW Post Decimation Sampling Rate = "<<result_sampling_rate
<<", decimation factor = "<<decimation_factor_<<endl;
return decimation_factor_;
}
template<typename TReal>
void habdec::Decoder<TReal>::process()
{
if( !iq_in_buffer_.samplingRate() ) // uninitialized
return;
using namespace std;
std::lock_guard<std::mutex> lock(process_mutex_);
bool b_debug = 0;
if(b_debug)
cout<<endl<<endl;
// copy samples from buffer to temp
{
lock_guard<mutex> _lock(iq_in_buffer_mtx_);
if( int(iq_in_buffer_.size()) < decimation_factor_)
{
if(b_debug)
cout<<"Decoder::process() "<<"iq_in_buffer_.size()) < decimation_factor_"<<endl;
return;
}
const size_t samples_to_decimate_cnt = iq_in_buffer_.size() - (iq_in_buffer_.size() % decimation_factor_);
iq_samples_temp_.resize(samples_to_decimate_cnt);
memcpy( iq_samples_temp_.data(), iq_in_buffer_.data(), samples_to_decimate_cnt * sizeof(TComplex) );
if(b_debug)
cout<<"Decoder::process() "<<"samples_to_decimate_cnt "<<samples_to_decimate_cnt<<" of "<<iq_in_buffer_.size()<<endl;
iq_in_buffer_.erase( iq_in_buffer_.begin(), iq_in_buffer_.begin()+samples_to_decimate_cnt );
}
// DECIMATE
//
size_t decimated_samples_size = iq_samples_temp_.size();
for(auto& _decimator : decimation_stages_)
{
_decimator.setInput ( iq_samples_temp_.data(), decimated_samples_size );
_decimator.setOutput( iq_samples_temp_.data() );
decimated_samples_size = _decimator();
}
iq_samples_temp_.resize( decimated_samples_size );
iq_samples_decimated_.insert( iq_samples_decimated_.end(), iq_samples_temp_.begin(), iq_samples_temp_.end() );
iq_samples_decimated_.samplingRate( getDecimatedSamplingRate() );
if(b_debug)
cout<<"Decoder::process() "<<"iq_samples_decimated_.size() "<<iq_samples_decimated_.size()<<endl;
// FFT
//
// collect at least fft_bins_cnt_ samples from decimation
if( freq_in_.size() < fft_bins_cnt_ && iq_samples_temp_.size() )
{
const size_t _to_push = min(fft_bins_cnt_-freq_in_.size(), iq_samples_temp_.size());
freq_in_.insert (
freq_in_.end(),
iq_samples_temp_.begin(), iq_samples_temp_.begin()+_to_push );
if(b_debug)
cout<<"Decoder::process() "<<"FFT _to_push "<<_to_push<<endl;
}
freq_in_.samplingRate( getDecimatedSamplingRate() );
freq_out_.samplingRate( getDecimatedSamplingRate() );
// fft compute
if(freq_in_.size() >= fft_bins_cnt_)
{
{
lock_guard<mutex> _lock(freq_out_mtx_);
freq_out_.resize(fft_bins_cnt_);
fft_.setInput( (float*) freq_in_.data(), fft_bins_cnt_ );
fft_.setOutput( (float*) freq_out_.data() );
fft_();
}
freq_in_.clear();
}
const size_t batch_size = 256; // why does it have to be 256 ?
if(iq_samples_decimated_.size() < batch_size)
{
if(b_debug)
cout<<"Decoder::process() "<<"iq_samples_decimated_.size() < batch_size : "<<iq_samples_decimated_.size()<<endl;
return;
}
// AFC
//
// scoped_lock _lock2(freq_out_mtx_, afc_mtx_); // c++17
if(unique_lock<mutex>(afc_mtx_, try_to_lock))
{
if(unique_lock<mutex>(freq_out_mtx_, try_to_lock))
{
if(freq_out_.size() == fft_bins_cnt_)
afc_.setFftSamples(freq_out_);
afc_();
}
}
double frequency_correction = getFrequencyCorrection();
double shift_Hz = afc_.getShift();
double nf, nv;
afc_.getNoiseFloor(nf, nv);
// cout<<frequency_correction<<"\t"<<shift_Hz<<"\t"<<nf<<"\t"<<nv<<endl;
// Not Decoding above certain sampling rate
//
if(getDecimatedSamplingRate() > 4*max_decimated_sampling_rate_)
{
iq_samples_temp_.clear();
iq_samples_decimated_.clear();
return;
}
// Low Pass FIR
//
const size_t samples_to_filter_cnt = iq_samples_decimated_.size() - iq_samples_decimated_.size() % batch_size;
iq_samples_filtered_.resize(samples_to_filter_cnt);
{
lock_guard<mutex> _lock(lowpass_fir_mtx_);
lowpass_fir_.setInput (iq_samples_decimated_.data(), samples_to_filter_cnt);
lowpass_fir_.setOutput(iq_samples_filtered_.data());
lowpass_fir_.LP_BlackmanHarris(lowpass_bw_, lowpass_trans_);
lowpass_fir_();
iq_samples_filtered_.samplingRate( getDecimatedSamplingRate() );
}
iq_samples_decimated_.erase( iq_samples_decimated_.begin(), iq_samples_decimated_.begin()+samples_to_filter_cnt );
if(b_debug)
cout<<"Decoder::process() "<<"FIR taps : "<<lowpass_fir_.taps_size()<<endl;
// Demod - converts frequency to amplitudes
//
{
lock_guard<mutex> _lock(demodulated_mtx_);
demodulated_.resize( iq_samples_filtered_.size() );
FSK2_Demod<TReal>(
iq_samples_filtered_.data(), iq_samples_filtered_.size(),
demodulated_.data() );
symbol_extractor_.samplingRate( getDecimatedSamplingRate() );
symbol_extractor_.pushSamples(demodulated_);
}
if(b_debug)
cout<<"Decoder::process() "<<"demodulated_.size() "<<demodulated_.size()<<endl;
// Symbol Extractor
//
symbol_extractor_();
vector<bool> symbols = symbol_extractor_.get();
if(b_debug)
cout<<"Decoder::process() "<<"symbols.size() "<<symbols.size()<<endl;
if(symbols.size())
{
rtty_.push(symbols);
rtty_();
}
if( !rtty_.size() )
return;
auto decoded_chars = rtty_.get();
rtty_char_stream_.insert( rtty_char_stream_.end(), decoded_chars.begin(), decoded_chars.end() );
if(live_print_)
{
for( auto c : decoded_chars )
cout<<c;
cout.flush();
}
// overflow protection
if(rtty_char_stream_.size() > 1000)
rtty_char_stream_.erase( 0, rtty_char_stream_.rfind('$') );
// scan for sentence from time to time
if( rtty_char_stream_.size() > 20 /*last_sentence_.size()/2*/ )
{
bool b_scan_for_sentence = true;
while(b_scan_for_sentence)
{
map<string,string> result = extractSentence(rtty_char_stream_);
if( result["success"] == "OK" )
{
rtty_char_stream_ = result["stream"]; // rest of stream after sentence
last_sentence_ = result["callsign"] + "," + result["data"] + "*" + result["crc"];
printHabhubSentence( result["callsign"], result["data"], result["crc"] );
if( success_callback_ &&
result["crc"] == CRC(result["callsign"] + "," + result["data"]) )
success_callback_( result["callsign"], result["data"], result["crc"] );
}
else
{
b_scan_for_sentence = false;
}
}
}
} // process()
template<typename TReal>
std::string Decoder<TReal>::getRTTY()
{
return rtty_char_stream_;
}
template<typename TReal>
std::string Decoder<TReal>::getLastSentence()
{
return last_sentence_;
}
template<typename TReal>
void Decoder<TReal>::baud(double i_baud)
{
std::lock_guard<std::mutex> _lock(process_mutex_);
symbol_extractor_.symbolRate(i_baud);
}
template<typename TReal>
double Decoder<TReal>::baud() const
{
return symbol_extractor_.symbolRate();
}
template<typename TReal>
void Decoder<TReal>::rtty_bits(size_t i_ascii_bits)
{
std::lock_guard<std::mutex> _lock(process_mutex_);
rtty_.ascii_bits(i_ascii_bits);
}
template<typename TReal>
size_t Decoder<TReal>::rtty_bits() const
{
return rtty_.ascii_bits();
}
template<typename TReal>
void Decoder<TReal>::rtty_stops(float i_ascii_stops)
{
std::lock_guard<std::mutex> _lock(process_mutex_);
rtty_.ascii_stops(i_ascii_stops);
}
template<typename TReal>
float Decoder<TReal>::rtty_stops() const
{
return rtty_.ascii_stops();
}
template<typename TReal>
int Decoder<TReal>::getDecimationFactor() const
{
//std::lock_guard<std::mutex> _lock(process_mutex_);
// this probably should be locked with process_mutex_
return decimation_factor_;
}
template<typename TReal>
double Decoder<TReal>::getInputSamplingRate() const
{
return iq_in_buffer_.samplingRate();
}
template<typename TReal>
double Decoder<TReal>::getDecimatedSamplingRate() const
{
return getInputSamplingRate() / getDecimationFactor();
}
template<typename TReal>
double Decoder<TReal>::getSymbolRate() const
{
return symbol_extractor_.symbolRate();
}
template<typename TReal>
size_t Decoder<TReal>::getBinsCount() const
{
return fft_bins_cnt_;
}
template<typename TReal>
const typename Decoder<TReal>::TIQVector Decoder<TReal>::getFFT() const
{
std::lock_guard<std::mutex> _lock(freq_out_mtx_);
return freq_out_;
}
template<typename TReal>
const typename Decoder<TReal>::TRVector Decoder<TReal>::getDemodulated() const
{
std::lock_guard<std::mutex> _lock(demodulated_mtx_);
return demodulated_;
}
template<typename TReal>
const typename Decoder<TReal>::TRVector Decoder<TReal>::getPowerSpectrum() const
{
std::lock_guard<std::mutex> _lock(afc_mtx_);
// std::this_thread::sleep_for( ( std::chrono::duration<double, std::milli>(1000) ));
return afc_.getPowerSpectrum();
}
template<typename TReal>
void Decoder<TReal>::getPeaks(int& pl, int& pr)
{
std::lock_guard<std::mutex> _lock(afc_mtx_);
afc_.getPeaks(pl, pr);
}
template<typename TReal>
void habdec::Decoder<TReal>::getNoiseFloor(double& nf, double& nv)
{
std::lock_guard<std::mutex> _lock(afc_mtx_);
afc_.getNoiseFloor(nf, nv);
}
template<typename TReal>
double habdec::Decoder<TReal>::getShift() const
{
return afc_.getShift();
}
template<typename TReal>
double habdec::Decoder<TReal>::getFrequencyCorrection() const
{
return afc_.getFrequencyCorrection();
}
template<typename TReal>
void habdec::Decoder<TReal>::resetFrequencyCorrection(double frequency_correction)
{
afc_.resetFrequencyCorrection(frequency_correction);
}
template<typename TReal>
SpectrumInfo<TReal> habdec::Decoder<TReal>::getSpectrumInfo()
{
SpectrumInfo<TReal> spectr_info;
spectr_info = getPowerSpectrum();
if(!spectr_info.size())
return spectr_info;
spectr_info.min_ = *std::min_element( spectr_info.cbegin(), spectr_info.cend() );
spectr_info.max_ = *std::max_element( spectr_info.cbegin(), spectr_info.cend() );
int pl, pr;
getPeaks(pl, pr);
spectr_info.peak_left_ = std::abs(pl);
spectr_info.peak_left_valid_ = pl>0;
spectr_info.peak_right_ = std::abs(pr);
spectr_info.peak_right_valid_ = pr>0;
getNoiseFloor(spectr_info.noise_floor_, spectr_info.noise_variance_);
spectr_info.sampling_rate_ = getDecimatedSamplingRate();
spectr_info.shift_ = getShift();
return spectr_info;
}
template<typename T>
std::ostream& operator<<( std::ostream& output, const std::vector<T>& v )
{
for(const auto& a : v)
output<<a<<" ";
return output;
}
}
// namespace habdec

Wyświetl plik

@ -0,0 +1,111 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#include "FFT.h"
#include <cstring>
#include <iostream>
#include <complex>
namespace habdec
{
FFT::~FFT()
{
if(size_)
fftwf_destroy_plan(fftw_plan_);
if(fft_in_)
fftwf_free(fft_in_);
if(fft_out_)
fftwf_free(fft_out_);
}
size_t FFT::size() const
{
return size_;
}
void FFT::setInput(float* p_input, const size_t i_size)
{
if(i_size != size_)
{
std::cout<<"FFT rebuild to "<<i_size<<std::endl;
if(size_)
fftwf_destroy_plan(fftw_plan_);
size_ = i_size;
if(fft_in_) fftwf_free(fft_in_);
if(fft_out_) fftwf_free(fft_out_);
fft_in_ = (fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex) * size_);
fft_out_= (fftwf_complex*) fftwf_malloc(sizeof(fftwf_complex) * size_);
fftw_plan_ = fftwf_plan_dft_1d(size_, fft_in_, fft_out_, FFTW_FORWARD, FFTW_ESTIMATE);
}
p_in_ = p_input;
}
void FFT::setOutput(float* p_output)
{
p_out_ = p_output;
}
void FFT::swap_half() // swaps values on other half of FFT result
{
if(!size())
return;
std::complex<float>* p_samples_float = reinterpret_cast<std::complex<float>*>(p_out_);
const size_t half = size()/2;
for(size_t i=0; i<half; ++i)
std::swap( p_samples_float[i], p_samples_float[i+half] );
}
void FFT::operator()()
{
if( p_in_ && p_out_ )
{
memcpy( (void*) fft_in_, p_in_, size() * sizeof(std::complex<float>) );
fftwf_execute(fftw_plan_);
memcpy( (void*) p_out_, fft_out_, size() * sizeof(std::complex<float>) );
swap_half();
}
else if(!p_in_)
{
std::cout<<"FFT No Input"<<std::endl;
}
else if(!p_out_)
{
std::cout<<"FFT No Output"<<std::endl;
}
}
} // namespace habdec

61
code/Decoder/FFT.h 100644
Wyświetl plik

@ -0,0 +1,61 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <memory>
#include <fftw3.h>
namespace habdec
{
class FFT
{
public:
FFT() = default;
FFT(const FFT&) = delete;
FFT& operator=(const FFT&) = delete;
~FFT();
void setInput(float* p_input, const size_t i_size);
void setOutput(float* p_output);
size_t size() const;
void operator()();
private:
void swap_half(); // swaps values on other half of FFT result
size_t size_ = 0;
float* p_in_ = 0;
float* p_out_ = 0;
// fftw stuff
fftwf_plan fftw_plan_;
fftwf_complex* fft_in_ = 0;
fftwf_complex* fft_out_ = 0;
};
} // namespace habdec

Wyświetl plik

@ -0,0 +1,46 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <complex>
namespace habdec
{
template<typename T>
void FSK2_Demod(
const std::complex<T>* p_cmplx_samples, const size_t samples_count,
T* o_demod )
{
// TO DO - this should not be static if threads...
static std::complex<T> last_value = p_cmplx_samples[0];
for(size_t i=1; i<samples_count; ++i)
o_demod[i] = std::arg( p_cmplx_samples[i] * std::conj(p_cmplx_samples[i-1]) );
o_demod[0] = std::arg( p_cmplx_samples[0] * std::conj(last_value) );
last_value = p_cmplx_samples[samples_count-1];
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,212 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cstring>
#include <memory>
#include <vector>
#include <iostream>
#include "habdec_windows.h"
namespace habdec
{
template<typename Ts, typename Tt> // Tsamples, Ttaps
class FirFilter
{
public:
bool setInput(const Ts* p_input, const size_t in_size);
bool setOutput(Ts*);
bool setFilter(const Tt*, const size_t taps_size);
size_t taps_size();
bool operator()();
void LP_BlackmanHarris(const float i_relative_filt_width, const float trans_bw = 0);
private:
const Ts* p_input_ = 0;
size_t p_input_size_ = 0;
Ts* p_output_ = 0;
std::vector<Tt> taps_;
std::vector<Ts> buff_;
void dotProduct();
};
template<typename Ts, typename Tt>
bool inline FirFilter<Ts, Tt>::operator()()
{
dotProduct();
return true;
}
template<typename Ts, typename Tt>
size_t inline FirFilter<Ts, Tt>::taps_size()
{
return taps_.size() ;
}
template<typename Ts, typename Tt>
bool inline FirFilter<Ts, Tt>::setInput(const Ts* p_input, const size_t in_size)
{
if(!p_input || !in_size)
return false;
p_input_ = p_input;
p_input_size_ = in_size;
return true;
}
template<typename Ts, typename Tt>
bool inline FirFilter<Ts, Tt>::setFilter(const Tt* p_filter, const size_t in_size)
{
if(!p_filter || !in_size)
return false;
taps_.resize(in_size);
memcpy( taps_.data(), p_filter, in_size * sizeof(Tt) );
return true;
}
template<typename Ts, typename Tt>
bool inline FirFilter<Ts, Tt>::setOutput(Ts* p_output)
{
if(!p_output)
return false;
p_output_ = p_output;
return true;
}
template<typename Ts, typename Tt>
void FirFilter<Ts, Tt>::dotProduct()
{
using namespace std;
if(!taps_.size())
{
cout<<"FirFilter::dotProduct() no taps. return."<<endl;
return;
}
if( taps_.size() > p_input_size_+1 )
{
cout<<"FirFilter::dotProduct() more taps than samples. return. "<<p_input_size_<<" "<<taps_.size()<<endl;
return;
}
if(p_input_ == p_output_)
{
cout<<"FirFilter::dotProduct() ERROR. in==out"<<endl;
return;
}
// reinit buffer if size changed
const size_t new_buff_size = p_input_size_ + taps_.size();
if(buff_.size() < new_buff_size)
{
// cout<<"FirFilter resize buff_ "<<p_input_size_<<" + "<<taps_.size()<<endl;
buff_.resize(new_buff_size);
memset( buff_.data(), 0, sizeof(Ts) * taps_.size() );
}
// copy samples to buffer, offseted by taps_count-1
memcpy( buff_.data() + taps_.size()-1,
p_input_,
p_input_size_ * sizeof(Ts) );
// inner product
for(size_t i=0; i<p_input_size_; ++i)
{
Ts accumulator = 0;
for(size_t t=0; t<taps_.size(); ++t)
accumulator += buff_[i+t] * taps_[t];
p_output_[i] = accumulator;
}
// wrapping. copy last part (taps_.size()-1) of (unfiltered) input signal to start of buffer
memcpy( buff_.data(),
p_input_ + p_input_size_ - (taps_.size() - 1),
// p_input_ + p_input_size_ - min(taps_.size()-1, p_input_size_),
(taps_.size()-1) * sizeof(Ts) );
}
template<typename Ts, typename Tt>
void FirFilter<Ts, Tt>::LP_BlackmanHarris(const float i_relative_filt_width, const float trans_bw)
{
if(!p_input_size_)
{
std::cout<<"FirFilter::LP_BlackmanHarris No Input set."<<std::endl;
return;
}
const float f_cut_rel = i_relative_filt_width;
const float _transition_bw = trans_bw ?
trans_bw : i_relative_filt_width*i_relative_filt_width;
size_t taps_sz = 4.0f/_transition_bw;
if(taps_sz>p_input_size_)
taps_sz = p_input_size_;
taps_sz |= 1; // must be odd number
if(taps_sz <= 4)
return;
if(taps_sz == taps_.size())
return;
taps_.resize(taps_sz);
double _sum = 0;
const int _mid = int(taps_sz/2); // !! INT IS VERY IMPORTANT HERE !!
for(int i=0; i<int(taps_sz); i++)
{
taps_[i] = sinc(2.0f*f_cut_rel*(i-_mid)) * BlackmanHarris<Tt>(size_t(i), taps_sz);
_sum += taps_[i];
}
// normalize taps_
for(size_t i=0; i<taps_sz; ++i)
taps_[i] /= _sum;
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,76 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <vector>
#include <complex>
#include <atomic>
namespace habdec
{
// IQ vector with sampling rate
//
template<typename T>
class IQVector : public std::vector< std::complex<T> >
{
public:
typedef T TValue;
typedef std::complex<T> TComplex;
IQVector() = default;
IQVector(const IQVector<T>& rhs);
IQVector<T> operator=(const IQVector<T>& rhs);
double samplingRate() const {return sampling_rate_;}
void samplingRate(const double i_samplingRate) {sampling_rate_ = i_samplingRate;}
private:
std::atomic<double> sampling_rate_ = {0};
};
template<typename T>
IQVector<T>::IQVector(const IQVector<T>& rhs) : std::vector< std::complex<T> >::vector(rhs)
{
sampling_rate_.store(rhs.sampling_rate_);
}
template<typename T>
IQVector<T> IQVector<T>::operator=(const IQVector<T>& rhs)
{
std::vector< std::complex<T> >::operator=(rhs);
sampling_rate_.store(rhs.sampling_rate_);
return *this;
}
template<typename T>
std::ostream& operator<<( std::ostream& output, const IQVector<T>& iqVector )
{
for(size_t i=0; i<iqVector.size(); ++i)
output<<iqVector[i]<<" ";
return output;
}
} // namespace habdec

141
code/Decoder/RTTY.h 100644
Wyświetl plik

@ -0,0 +1,141 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "stddef.h"
#include <vector>
#include <iostream>
#include <cctype>
#include "common/console_colors.h"
namespace habdec
{
template<typename TBit>
class RTTY
{
public:
void ascii_bits(size_t i_bits) {nbits_ = i_bits;};
size_t ascii_bits() const {return nbits_;};
void ascii_stops(float i_stops) {nstops_ = i_stops;};
float ascii_stops() const {return nstops_;};
void push(const std::vector<TBit>& i_bits);
size_t size() {return chars_.size();}
std::vector<char> get();
size_t operator()();
private:
size_t nbits_ = 0;
float nstops_ = 0;
std::vector<TBit> bits_;
std::vector<char> chars_;
};
template<typename TBit>
void RTTY<TBit>::push(const std::vector<TBit>& i_bits)
{
using namespace std;
bits_.insert( bits_.end(), i_bits.begin(), i_bits.end() );
}
template<typename TBit>
std::vector<char> RTTY<TBit>::get()
{
auto res = chars_;
chars_.clear();
return res;
}
template<typename TBit>
size_t RTTY<TBit>::operator()()
{
if(!nbits_ && !nstops_)
return 0;
if( bits_.size() < (1+nbits_+nstops_) )
return 0;
using namespace std;
size_t decoded_chars = 0;
size_t last_decoded_bit_index = 0;
for(size_t i=0; i<bits_.size()/*-char_bitlen*/; /**/)
{
bool is_char_seq =
bits_[i] == 0; // start bit?
// at least 1+8+2 bits available ?
is_char_seq &= (i + 1+nbits_+nstops_) <= bits_.size();
// has stop bits ?
for(size_t s=0; s<nstops_; ++s)
is_char_seq &= bits_[i+1+nbits_ + s] == 1;
if( !is_char_seq )
{
++i;
continue;
}
// this has to be char sequence
{
++i;
// bit to char
char c = 0;
for(size_t _c=0; _c<nbits_; ++_c)
{
c += bits_[i] << _c;
++i;
}
if( isprint(c) || c == '\n' )
{
chars_.push_back(c);
++decoded_chars;
}
i += nstops_;
last_decoded_bit_index = i-1; // points to last stop bit
}
}
if(last_decoded_bit_index)
bits_.erase( bits_.begin(), bits_.begin() + last_decoded_bit_index + 1 );
return decoded_chars;
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,89 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <vector>
#include <iostream>
namespace habdec
{
/*
just a vector with spectrum power values
and some extra info
*/
template<typename T>
class SpectrumInfo : public std::vector<T>
{
public:
typedef T TValue;
mutable T min_ = 0;
mutable T max_ = 0;
mutable double noise_floor_ = 0;
mutable double noise_variance_ = 0;
mutable double sampling_rate_ = 0;
mutable double shift_ = 0;
mutable int peak_left_ = 0;
mutable int peak_right_ = 0;
mutable bool peak_left_valid_ = false;
mutable bool peak_right_valid_ = false;
SpectrumInfo() = default;
template<typename U>
SpectrumInfo(const SpectrumInfo<U>& rhs) :
std::vector<T>::vector(rhs),
noise_floor_(rhs.noise_floor_),
noise_variance_(rhs.noise_variance_),
peak_left_(rhs.peak_left_),
peak_right_(rhs.peak_right_),
peak_left_valid_(rhs.peak_left_valid_),
peak_right_valid_(rhs.peak_right_valid_)
{
//
}
template<typename U>
const SpectrumInfo<T>& operator=(const SpectrumInfo<U>& rhs)
{
std::vector<T>::operator=(rhs);
noise_floor_ = rhs.noise_floor_;
noise_variance_ = rhs.noise_variance_;
peak_left_ = rhs.peak_left_;
peak_right_ = rhs.peak_right_;
peak_left_valid_ = rhs.peak_left_valid_;
peak_right_valid_ = rhs.peak_right_valid_;
return *this;
}
const SpectrumInfo<T>& operator=(const std::vector<T>& rhs)
{
std::vector<T>::operator=(rhs);
return *this;
}
};
} // namespace habdec

Wyświetl plik

@ -0,0 +1,261 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cmath>
#include <vector>
#include <iostream>
#include <algorithm>
#include <numeric>
namespace
{
template <typename T>
inline int sgn(T val)
{
return (T(0) < val) - (val < T(0));
}
template <typename T>
inline int _dir(T left, T right)
{
if( sgn(left) < sgn(right) )
return 1;
else if( sgn(left) > sgn(right) )
return -1;
else
return 0;
}
template<typename TReal, typename TRVector>
void FlipPointAvrg(
const TRVector& v,
const size_t i,
const size_t R,
TReal& o_avg_l,
TReal& o_avg_r )
{
using namespace std; int _L = max(int(i-R), 0); // left bound
int _R = min(i+R, v.size()); // right bound
o_avg_l = std::accumulate(v.begin()+_L, v.begin()+i, TReal(0)) / (i-_L);
o_avg_r = std::accumulate(v.begin()+i, v.begin()+_R, TReal(0)) / (_R-i);
}
} // namespace
namespace habdec
{
template<typename TReal>
class SymbolExtractor
{
public:
typedef std::vector<TReal> TRVector;
void pushSamples(const TRVector& v); //REAL samples after Freq demodulation
void samplingRate(const double sm_r) { sampling_rate_ = sm_r; }
double samplingRate() const { return sampling_rate_; }
void symbolRate(const double sb_r) { symbol_rate_ = sb_r; } // baud
double symbolRate() const { return symbol_rate_; }
std::vector<bool> get(size_t count=0);
size_t samplesPerBit() const { return size_t(round( samplingRate()/symbolRate() )); }
void operator()();
private:
double sampling_rate_ = 0;
double symbol_rate_ = 1;
TRVector samples_;
std::vector<bool> bits_;
size_t findFirstFlipPoint(const size_t start_offset);
std::vector<size_t> findFlipPoints();
};
template<typename TReal>
void SymbolExtractor<TReal>::pushSamples(const TRVector& v)
{
using namespace std;
if(!v.size())
return;
// safety vent
if(samples_.size() > 1e6)
{
cout<<"SymbolExtractor::pushSamples overflow. Delete samples."<<endl;
samples_.clear();
}
const size_t prev_size = samples_.size();
samples_.resize( samples_.size() + v.size() );
memcpy( samples_.data() + prev_size, v.data(), v.size() * sizeof(TReal) );
}
template<typename TReal>
void SymbolExtractor<TReal>::operator()()
{
if( !sampling_rate_ || !symbol_rate_ )
return;
if( samples_.size() < samplingRate()/symbolRate()*3 ) // have at least 3 symbols
return;
std::vector<size_t> flip_points = findFlipPoints();
if(!flip_points.size())
return;
size_t last_flip_point = 0;
for(const auto flip_point : flip_points)
{
TReal avg = TReal(
std::accumulate( samples_.begin()+last_flip_point,
samples_.begin()+flip_point, (TReal)0 )
) / (flip_point-last_flip_point);
bool bit_value = avg > 0;
size_t bit_count = size_t( round( float(flip_point-last_flip_point) / float(samplesPerBit()) ) );
last_flip_point = flip_point;
while(bit_count--)
bits_.push_back(bit_value);
}
size_t erase_to = std::min(last_flip_point, samples_.size());
samples_.erase( samples_.begin(), samples_.begin() + erase_to );
}
template<typename TReal>
size_t SymbolExtractor<TReal>::findFirstFlipPoint(const size_t start_offset)
{
if( (samples_.size()-start_offset) < samplesPerBit() )
return 0;
// FIND FIRST FLIP POINT
// IT NEEDS TO HAVE DIFFERENT SIGN OF AVERAGE
// ON IT'S LEFT AND RIGHT SIDE OF LENGTH R
const size_t R = std::max(4, int(samplesPerBit() / 4));
std::vector<size_t> flip_points;
// start at R
size_t flip_point = start_offset + R;
TReal avg_left;
TReal avg_right;
FlipPointAvrg(samples_, flip_point, R, avg_left, avg_right);
// SCAN UNTIL FIRST FLIP_POINT
while(sgn(avg_left) == sgn(avg_right))
{
flip_point += 1;
if(flip_point >= (samples_.size() - samplesPerBit()))
return 0;
FlipPointAvrg(samples_, flip_point, R, avg_left, avg_right);
}
size_t flip_point_left = flip_point;
// int value_change_dir = _dir(avg_left, avg_right);
// SCAN UNTIL LAST FLIP_POINT WITH CHANGING SIGN OF AVERAGE
while(sgn(avg_left) != sgn(avg_right))
{
flip_point += 1;
if(flip_point >= (samples_.size() - samplesPerBit()))
return 0;
FlipPointAvrg(samples_, flip_point, R, avg_left, avg_right);
}
size_t flip_point_right = flip_point;
// in range [flip_point_left, flip_point_right)
// find point with largest difference in average values
std::vector<size_t> flip_point_candidates;
std::vector<float> flip_point_candidates_weight;
for(size_t i=flip_point_left; i<flip_point_right; ++i)
{
FlipPointAvrg(samples_, i, R, avg_left, avg_right);
flip_point_candidates.push_back(i);
flip_point_candidates_weight.push_back( abs(avg_right-avg_left) );
}
auto p_max = max_element(flip_point_candidates_weight.begin(), flip_point_candidates_weight.end());
size_t max_index = p_max - flip_point_candidates_weight.begin();
return flip_point_candidates[max_index];
}
template<typename TReal>
std::vector<size_t> SymbolExtractor<TReal>::findFlipPoints()
{
size_t offset = 0;
size_t flip_point = findFirstFlipPoint(offset);
std::vector<size_t> all_points;
while(flip_point)
{
all_points.push_back(flip_point);
offset = flip_point;
flip_point = findFirstFlipPoint(offset);
}
return all_points;
}
template<typename TReal>
std::vector<bool> SymbolExtractor<TReal>::get(size_t count)
{
if(count == 0)
count = bits_.size();
const size_t _count = std::min(count, bits_.size());
const std::vector<bool> res( bits_.begin(), bits_.begin() + _count );
bits_.erase( bits_.begin(), bits_.begin() + _count );
return res;
}
} // namespace habdec

Plik diff jest za duży Load Diff

Wyświetl plik

@ -0,0 +1,142 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
// fancy decorator to measure execution time
// #if defined(__cpp_decltype_auto)
#if 0
#define FUNC_TIMER 1
#include <type_traits>
#include <utility>
#include <iostream>
#include <chrono>
//https://stackoverflow.com/questions/28498852/c-function-decorator/33642149
namespace habdec
{
template <class T>
struct RetWrapper
{
template <class Tfunc, class... Targs>
RetWrapper(Tfunc &&func, Targs &&... args)
: val(std::forward<Tfunc>(func)(std::forward<Targs>(args)...)) {}
//T&& value() { return std::move(val); }
T value() { return val; }
private:
T val;
};
template <>
struct RetWrapper<void>
{
template <class Tfunc, class... Targs>
RetWrapper(Tfunc &&func, Targs &&... args)
{
std::forward<Tfunc>(func)(std::forward<Targs>(args)...);
}
void value() {}
};
//template <class Tfunc, class Tbefore, class Tafter>
template <class Tfunc>
//auto decorate(Tfunc &&func, Tbefore &&before, Tafter &&after)
auto AddTimer(Tfunc&& func, std::string name)
{
return [
func = std::forward<Tfunc>(func),
name
//before = std::forward<Tbefore>(before),
//after = std::forward<Tafter>(after)
] (auto&& ... args) -> decltype(auto)
{
//before(std::forward<decltype(args)>(args)...);
using namespace std;
typedef chrono::microseconds DurT;
static int count = 0;
static DurT dur_min = DurT::max();
static DurT dur_max = DurT::min();
static DurT dur_sum = DurT::zero();
static auto time_start = chrono::high_resolution_clock::now();
auto _start = chrono::high_resolution_clock::now();
////////////////////////////////////////////////////////////
RetWrapper<std::result_of_t<Tfunc(decltype(args)...)>> ret(
func, std::forward<decltype(args)>(args)...
);
////////////////////////////////////////////////////////////
auto _end = chrono::high_resolution_clock::now();
DurT _duration = chrono::duration_cast<DurT>(_end - _start);
++count;
dur_sum += _duration;
if(_duration < dur_min)
dur_min = _duration;
if(_duration > dur_max)
dur_max = _duration;
if( chrono::duration_cast<chrono::milliseconds>(
chrono::high_resolution_clock::now() - time_start).count() >= 1000
)
{
DurT avg = dur_sum / count;
#define FUNC_TIMER_NO_PRINT 1
#if !defined(FUNC_TIMER_NO_PRINT)
cout<<name<<" stats. "
<<" min:"<<dur_min.count()/1e3<<"ms"
<<" avg:"<<avg.count()/1e3<<"ms"
<<" max:"<<dur_max.count()/1e3<<"ms"
<<" "<<count<<"/s"<<endl;
#endif
count = 0;
dur_min = DurT::max();
dur_max = DurT::min();
dur_sum = DurT::zero();
time_start = chrono::high_resolution_clock::now();
}
//after(std::forward<decltype(args)>(args)...);
// does not work if return directly
return ret.value();
//auto result = ret.value();
//return result;
};
}
} // namespace habdec
#endif //#if defined(__cpp_nontype_template_parameter_auto)

Wyświetl plik

@ -0,0 +1,53 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <cmath>
#include <cstring>
template<typename T_flt_>
inline T_flt_ sinc(T_flt_ x)
{
if(x)
return sin(x)/x;
else
return 1;
}
template<typename T_flt_> // float like types...
inline T_flt_ BlackmanHarris(const size_t x, const size_t N)
{
static const T_flt_ a0 = 0.35874;
static const T_flt_ a1 = 0.48829;
static const T_flt_ a2 = 0.14128;
static const T_flt_ a3 = 0.01168;
static const T_flt_ PI2 = 2.0*M_PI;
static const T_flt_ PI4 = 4.0*M_PI;
static const T_flt_ PI6 = 6.0*M_PI;
const T_flt_ N_1 = N-1;
T_flt_ w = a0 - a1*cos(PI2*x / N_1) + a2*cos(PI4*x / N_1) - a3*cos(PI6*x / N_1);
return w;
}

Wyświetl plik

@ -0,0 +1,65 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#include "print_habhub_sentence.h"
#include <iostream>
#include <iomanip>
#include "CRC.h"
#include "common/console_colors.h"
namespace habdec
{
void printHabhubSentence(
const std::string& callsign,
const std::string& data,
const std::string in_crc )
{
using namespace std;
static int success = 0;
static int failure = 0;
if( in_crc == CRC(callsign + string(",") + data) )
{
cout<<C_CLEAR<<'\r'<<""<<C_MAGENTA
<<callsign + string(",") + data + string("*") + in_crc
<<" OK"<<C_OFF;
++success;
}
else
{
cout<<C_CLEAR<<'\r'<<""<<C_RED
<<callsign + string(",") + data + string("*") + in_crc
<<" ERR"<<C_OFF;
++failure;
}
cout<<"\t\tOK:"<<success
<< " ERR:"<<failure
<<" Ratio:"<<setprecision(2)<<(float(success)/(success+failure));
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,33 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
namespace habdec
{
void printHabhubSentence(
const std::string& callsign,
const std::string& data,
const std::string in_crc );
} // namespace habdec

Wyświetl plik

@ -0,0 +1,70 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sentence_extract.h"
#include <iostream>
namespace habdec
{
std::regex HABHUB_REGEX( R"_(.*?(\$+)([\w,\-]+?),(.+?)(\*|\$)(\w\w\w\w).*)_" );
std::map<std::string,std::string> extractSentence(std::string stream)
{
using namespace std;
// replace '\n' in stream with spaces, otherwise regex will fail (C++ 11 issue)
replace( stream.begin(), stream.end(), '\n', ' ');
map<string,string> result;
result["success"] = string("ERR");
const int CRC_LEN = 4; // usually 4 chars after *
if(stream.find("*") < string::npos-CRC_LEN)
{
smatch match;
regex_match(stream, match, HABHUB_REGEX);
if(match.size() >= 5)
{
const string callsign = match[2];
const string data = match[3];
const string data_end = match[4]; // * or another $
const string _crc = match[5];
const size_t cut = min( stream.size(), size_t(match.position(4)+CRC_LEN) );
stream = stream.substr( cut );
result["success"] = string("OK");
result["callsign"] = callsign;
result["data"] = data;
result["crc"] = _crc;
result["stream"] = stream;
}
}
return result;
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,34 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <map>
#include <iostream>
#include <regex>
namespace habdec
{
std::map<std::string,std::string> extractSentence(std::string i_str);
} // namespace habdec

Wyświetl plik

@ -0,0 +1,29 @@
#include_directories( ${PROJECT_SOURCE_DIR} )
include_directories( ${CMAKE_CURRENT_SOURCE_DIR} )
find_package(SoapySDR REQUIRED) # this reverts CMAKE_CXX_STANDARD to '11'
#set ( CMAKE_CXX_STANDARD 17 )
include_directories( ${SoapySDR_INCLUDE_DIRS} )
message( "SoapySDR_INCLUDE_DIRS:" ${SoapySDR_INCLUDE_DIRS} )
message( "SoapySDR_LIBRARIESL:" ${SoapySDR_LIBRARIES} )
# RTTY DECODER
set ( IQSource_src
IQSource_File.h
IQSource.h
IQSource_SoapySDR.h IQSource_SoapySDR.cpp
)
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 " -O3 " )
endif()
add_library( IQSource ${IQSource_src})
target_link_libraries( IQSource ${SoapySDR_LIBRARIES} )

Wyświetl plik

@ -0,0 +1,46 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <cstddef>
namespace habdec
{
class IQSource
{
public:
virtual bool init() = 0;
virtual bool start() = 0;
virtual bool stop() = 0;
virtual bool isRunning() const = 0;
virtual std::string type() const = 0;
virtual size_t count() const = 0;
virtual size_t get(void* p_data, const size_t i_count) = 0;
virtual double samplingRate() const = 0;
virtual bool setOption(const std::string& option, const void* p_data) = 0;
virtual bool getOption(const std::string& option, void* p_data) = 0;
};
} // namespace habdec

Wyświetl plik

@ -0,0 +1,262 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "IQSource.h"
#include <memory>
#include <iostream>
#include <fstream>
#include <thread>
#include <stdio.h>
#include <SoapySDR/Device.hpp>
#include <SoapySDR/Formats.hpp>
namespace habdec
{
template<typename T>
class IQSource_File : public habdec::IQSource
{
public:
typedef T TValue;
typedef std::complex<T> TComplex;
bool start();
bool stop();
bool isRunning() const;
size_t count() const;
size_t get(void* p_data, const size_t i_count);
std::string type() const {return std::string("File");};
double samplingRate() const;
bool setOption(const std::string& option, const void* p_data);
bool getOption(const std::string& option, void* p_data);
bool init();
~IQSource_File();
private:
bool b_is_running_ = false;
bool b_is_realtime_ = true;
bool b_loop_ = false;
std::ifstream file_handle_;
std::string file_path_;
double sampling_rate_ = 0;
size_t count_ = 0;
};
} // namespace
namespace
{
std::ifstream::pos_type filesize(const char* filename)
{
std::ifstream in(filename, std::ifstream::ate | std::ifstream::binary);
return in.tellg();
}
} // namespace
namespace habdec
{
template<typename T>
bool IQSource_File<T>::start()
{
if(!file_handle_.is_open())
return false;
b_is_running_ = true;
return true;
}
template<typename T>
bool IQSource_File<T>::stop()
{
if(!file_handle_.is_open())
return false;
b_is_running_ = true;
return true;
}
template<typename T>
bool IQSource_File<T>::isRunning() const
{
if(!file_handle_.is_open())
return false;
return b_is_running_;
}
template<typename T>
size_t IQSource_File<T>::count() const
{
return count_;
}
template<typename T>
size_t IQSource_File<T>::get(void* p_data, const size_t i_count)
{
using namespace std;
if(!file_handle_.is_open())
{
std::cout<<"file_handle_ == 0"<<std::endl;
return 0;
}
if(!isRunning())
{
std::cout<<"Not Running."<<std::endl;
return 0;
}
if( file_handle_.eof() )
{
if(b_loop_)
{
cout<<file_path_<<" EOF. REWIND."<<endl;
file_handle_.clear();
file_handle_.seekg(0);
}
else
{
cout<<file_path_<<" EOF."<<endl;
return 0;
}
}
// READ DATA
file_handle_.read( reinterpret_cast<char*>(p_data), min(i_count, count_) * sizeof(TComplex) );
const size_t read_count = file_handle_.gcount() / sizeof(TComplex);
if(!file_handle_)
{
if(read_count != i_count)
cout<<"IQSource_File<T>::get() read less than desired: "<<read_count<<" of "<<i_count<<endl;
}
if(b_is_realtime_)
{
size_t wait = double(read_count) / sampling_rate_ * 1000;
std::this_thread::sleep_for( std::chrono::duration<double, std::milli>(wait) );
}
return read_count;
}
template<typename T>
double IQSource_File<T>::samplingRate() const
{
return sampling_rate_;
}
template<typename T>
IQSource_File<T>::~IQSource_File()
{
if(file_handle_)
{
stop();
// fclose(file_handle_);
file_handle_.close();
}
}
template<typename T>
bool IQSource_File<T>::init()
{
count_ = filesize( file_path_.c_str() ) / sizeof(TComplex);
file_handle_.open( file_path_, std::ios::binary );
if(!file_handle_.is_open())
return false;
return true;
}
template<typename T>
bool IQSource_File<T>::setOption(const std::string& option, const void* p_data)
{
void* p_data_nonconst = const_cast<void*>(p_data);
if(option == "file_string")
{
file_path_ = *reinterpret_cast<std::string*>(p_data_nonconst);
}
if(option == "sampling_rate_double")
{
sampling_rate_ = *reinterpret_cast<double*>(p_data_nonconst);
}
else if(option == "realtime_bool")
{
b_is_realtime_ = *reinterpret_cast<bool*>(p_data_nonconst);
}
else if(option == "loop_bool")
{
b_loop_ = *reinterpret_cast<bool*>(p_data_nonconst);
}
else
{
std::cout<<"IQSource_File::setOption error. Unknown option: "<<option<<std::endl;
return false;
}
return true;
}
template<typename T>
bool IQSource_File<T>::getOption(const std::string& option, void* p_data)
{
if(option == "file_string")
{
*reinterpret_cast<std::string*>(p_data) = file_path_;
}
if(option == "sampling_rate_double")
{
*reinterpret_cast<double*>(p_data) = sampling_rate_;
}
else if(option == "realtime_bool")
{
*reinterpret_cast<bool*>(p_data) = b_is_realtime_;
}
else if(option == "loop_bool")
{
*reinterpret_cast<bool*>(p_data) = b_loop_;
}
else
{
std::cout<<"IQSource_File::getOption error. Unknown option: "<<option<<std::endl;
return false;
}
return true;
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,415 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#include "IQSource_SoapySDR.h"
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <stdexcept>
#include <SoapySDR/Device.hpp>
#include <SoapySDR/Formats.hpp>
#include <SoapySDR/Errors.hpp>
namespace habdec
{
bool IQSource_SoapySDR::start()
{
if(!p_device_)
return false;
int result = 0;
if(!b_is_running_)
result = p_device_->activateStream(p_stream_);
if(result)
{
std::cout<<"IQSource_SoapySDR::start error. "<<SoapySDR::errToStr(result)<<std::endl;
return false;
}
b_is_running_ = true;
return true;
}
bool IQSource_SoapySDR::stop()
{
if(!p_device_)
return false;
int result = 0;
if(b_is_running_)
result = p_device_->deactivateStream(p_stream_);
if(result)
{
std::cout<<"IQSource_SoapySDR::stop error. "<<SoapySDR::errToStr(result)<<std::endl;
return false;
}
b_is_running_ = false;
return true;
}
bool IQSource_SoapySDR::isRunning() const
{
if(!p_device_)
return false;
return b_is_running_;
}
size_t IQSource_SoapySDR::count() const
{
return 0;
}
size_t IQSource_SoapySDR::get(void* p_data, const size_t i_count)
{
if(!p_device_)
{
std::cout<<"p_device_ == 0"<<std::endl;
return 0;
}
if(!p_stream_)
{
std::cout<<"p_stream_ == 0"<<std::endl;
return 0;
}
if(!isRunning())
{
std::cout<<"Not Running."<<std::endl;
return 0;
}
// const size_t buffs_size = 1;
void* buffs[1] = { reinterpret_cast<void*>(p_data) };
int reveice_flags = 0;
long long time_ns = 0;
const int result = p_device_->readStream(p_stream_, buffs, i_count, reveice_flags, time_ns);
if(result<0)
{
std::cout<<"IQSource_SoapySDR::get error."<<SoapySDR::errToStr(result)<<std::endl;
return 0;
}
return static_cast<size_t>(result);
}
double IQSource_SoapySDR::samplingRate() const
{
return sampling_rate_;
}
IQSource_SoapySDR::~IQSource_SoapySDR()
{
if(p_device_)
{
stop();
p_device_->closeStream(p_stream_);
//SoapySDR::Device::unmake(p_device_.get());
}
}
bool IQSource_SoapySDR::init()
{
p_device_.reset( SoapySDR::Device::make(soapysdr_kwargs_) );
if(!p_device_)
return false;
using namespace std;
cout<<"IQSource_SoapySDR::init"<<endl;
const string driver_key = p_device_->getDriverKey();
cout<<'\t'<<"driver_key "<<driver_key<<endl;
hwinfo_hwkey_ = p_device_->getHardwareKey();
const auto serial_it = soapysdr_kwargs_.find("serial");
if(serial_it != soapysdr_kwargs_.end())
hwinfo_serial_ = serial_it->second;
// hw info
// cout<<'\t'<<"hw_info:"<<endl;
const SoapySDR::Kwargs hw_info = p_device_->getHardwareInfo();
for(const auto& it : hw_info)
{
// cout<<"\t\tproperty:: "<<it.first<<":"<<it.second<<endl;
const string property = it.first;
// cout<<"Prop "<<property<<endl;
try {
if(property == "device_id")
{
hwinfo_device_id_ = std::stof(it.second);
}
}
catch(std::invalid_argument& e) {
cout<<"Failed argument conversion for "<<property<<endl;
}
}
// gains
hwinfo_gains_.clear();
for(const auto gain : p_device_->listGains(SOAPY_SDR_RX,0))
hwinfo_gains_.push_back(gain);
// freq range
const SoapySDR::RangeList freq_range_list = p_device_->getFrequencyRange(SOAPY_SDR_RX, 0);
hwinfo_freq_min_ = freq_range_list.front().minimum();
hwinfo_freq_max_ = freq_range_list.back().maximum();
// sampling rates
hwinfo_sampling_rates_ = p_device_->listSampleRates(SOAPY_SDR_RX, 0);
sort(hwinfo_sampling_rates_.begin(), hwinfo_sampling_rates_.end());
// stream formats
hwinfo_stream_formats_.clear();
for(const auto stream_format : p_device_->getStreamFormats(SOAPY_SDR_RX, 0)) // doubles
hwinfo_stream_formats_.push_back(stream_format);
// gain range
const SoapySDR::Range gain_range = p_device_->getGainRange(SOAPY_SDR_RX, 0);
hwinfo_gain_min_ = gain_range.minimum();
hwinfo_gain_max_ = gain_range.maximum();
// init
sampling_rate_ = hwinfo_sampling_rates_.back();
if(hwinfo_hwkey_ != "Airspy")
sampling_rate_ = hwinfo_sampling_rates_[3];
p_device_->setSampleRate(SOAPY_SDR_RX, 0, sampling_rate_);
p_device_->setGain( SOAPY_SDR_RX, 0, (hwinfo_gain_max_ - hwinfo_gain_min_)/2 );
p_device_->setFrequency( SOAPY_SDR_RX, 0, 434274500 );
p_stream_ = p_device_->setupStream(SOAPY_SDR_RX, SOAPY_SDR_CF32);
// PRINT INFO
/////////////////
// hw info
cout<<'\t'<<"hw_key "<<hwinfo_hwkey_<<endl;
cout<<'\t'<<"device_id "<<hwinfo_device_id_<<endl;
cout<<'\t'<<"serial "<<hwinfo_serial_<<endl;
// gains
cout<<"\tGains:\t";
for(const auto& gain : hwinfo_gains_)
cout<<gain<<", ";
cout<<endl;
cout<<"\tGain Range: "<<hwinfo_gain_min_<<" "<<hwinfo_gain_max_<<endl;
// freq range
cout<<"\tFreq Range: "<<hwinfo_freq_min_<<" "<<hwinfo_freq_max_<<endl;
// sampling rates
cout<<"\tSampling Ranges: ";
for(const auto sampling_rate : hwinfo_sampling_rates_)
cout<<sampling_rate<<", ";
cout<<endl;
// stream formats
cout<<"\tStream Formats: ";
for(const auto stream_format : hwinfo_stream_formats_)
cout<<stream_format<<", ";
cout<<endl;
// others
// nothing for AirSpy
cout<<"\tFrontend mapping:"<<p_device_->getFrontendMapping(SOAPY_SDR_RX)<<endl;
// nothing for AirSpy
cout<<"\tBandwidths: ";
for(const auto bandwidth : p_device_->listBandwidths(SOAPY_SDR_RX, 0)) // doubles
cout<<bandwidth<<", ";
cout<<endl;
cout<<"\tHas DC Offset: "<<p_device_->hasDCOffsetMode(SOAPY_SDR_RX, 0)<<endl;
cout<<"\tHas Freq Correction: "<<p_device_->hasFrequencyCorrection(SOAPY_SDR_RX, 0)<<endl;
return true;
}
bool IQSource_SoapySDR::setOption(const std::string& option, const void* p_data)
{
using namespace std;
void* p_data_nonconst = const_cast<void*>(p_data);
bool b_verbose = false;
if(option == "SoapySDR_Kwargs")
{
soapysdr_kwargs_ = *reinterpret_cast<SoapySDR::Kwargs*>(p_data_nonconst);
return true;
}
if(!p_device_)
{
cout<<"IQSource_SoapySDR::setOption no device initialized."<<endl;
}
if(option == "sampling_rate_double")
{
double value = *reinterpret_cast<double*>(p_data_nonconst);
cout<<"Setting "<<option<<" = "<<value<<endl;
if(p_device_)
{
p_device_->setSampleRate(SOAPY_SDR_RX, 0, value);
sampling_rate_ = p_device_->getSampleRate(SOAPY_SDR_RX, 0);
cout<<"Set "<<option<<" = "<<sampling_rate_<<endl;
}
return true;
}
else if(option == "frequency_double")
{
double value = *reinterpret_cast<double*>(p_data_nonconst);
if(p_device_)
{
if(b_verbose)
cout<<"Set "<<option<<" = "<<setprecision(12)<<value<<endl;
p_device_->setFrequency( SOAPY_SDR_RX, 0, value );
}
return true;
}
else if(option == "gain_double")
{
double value = *reinterpret_cast<double*>(p_data_nonconst);
if(p_device_)
{
p_device_->setGain( SOAPY_SDR_RX, 0, value );
if(b_verbose)
cout<<"Set "<<option<<" = "<<value<<endl;
}
return true;
}
else if(option == "biastee_double")
{
double value = *reinterpret_cast<double*>(p_data_nonconst);
if(p_device_)
{
if(b_verbose)
cout<<"Set "<<option<<" = "<<setprecision(12)<<value<<endl;
if(value)
p_device_->writeSetting("biastee", "true");
else
p_device_->writeSetting("biastee", "false");
}
return true;
}
else
{
cout<<"IQSource_SoapySDR::setOption error. Unknown option: "<<option<<endl;
return false;
}
return false;
}
bool IQSource_SoapySDR::getOption(const std::string& option, void* p_data)
{
using namespace std;
bool b_verbose = false;
if(!p_device_)
{
cout<<"IQSource_SoapySDR::setOption no device initialized."<<endl;
}
if(option == "sampling_rate_double")
{
*reinterpret_cast<double*>(p_data) = sampling_rate_;
if(b_verbose)
cout<<"getOption "<<option<<" "<<*reinterpret_cast<double*>(p_data)<<endl;
return true;
}
else if(option == "frequency_double")
{
if(p_device_)
{
*reinterpret_cast<double*>(p_data) = p_device_->getFrequency( SOAPY_SDR_RX, 0);
if(b_verbose)
cout<<"getOption "<<option<<" "<<*reinterpret_cast<double*>(p_data)<<endl;
return true;
}
return false;
}
else if(option == "gain_double")
{
if(p_device_)
{
*reinterpret_cast<double*>(p_data) = p_device_->getGain( SOAPY_SDR_RX, 0 );
if(b_verbose)
cout<<"getOption "<<option<<" "<<*reinterpret_cast<double*>(p_data)<<endl;
return true;
}
return false;
}
else if(option == "biastee_double")
{
if(p_device_)
{
double biastee_val =
p_device_->readSetting("biastee") == string("true");
*reinterpret_cast<double*>(p_data) = biastee_val;
if(b_verbose)
cout<<"getOption "<<option<<" "<<biastee_val<<endl;
return true;
}
return false;
}
else
{
cout<<"IQSource_SoapySDR::getOption error. Unknown option: "<<option<<endl;
return false;
}
return false;
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,77 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "IQSource.h"
#include <memory>
#include <vector>
#include <SoapySDR/Device.hpp>
#include <SoapySDR/Formats.hpp>
namespace habdec
{
class IQSource_SoapySDR : public habdec::IQSource
{
public:
~IQSource_SoapySDR();
bool start();
bool stop();
bool isRunning() const;
size_t count() const;
size_t get(void* p_data, const size_t i_count);
std::string type() const {return std::string("SoapySDR");};
double samplingRate() const;
bool setOption(const std::string& option, const void* p_data);
bool getOption(const std::string& option, void* p_data);
bool init();
private:
std::unique_ptr<SoapySDR::Device> p_device_ = 0;
SoapySDR::Stream* p_stream_ = 0;
bool b_is_running_ = false;
double sampling_rate_ = 0;
// SoapySDR hardware info
SoapySDR::Kwargs soapysdr_kwargs_; // used for init()
std::string hwinfo_hwkey_;
std::string hwinfo_serial_;
size_t hwinfo_device_id_;
std::vector<std::string> hwinfo_gains_;
std::vector<double> hwinfo_sampling_rates_;
std::vector<std::string> hwinfo_stream_formats_;
double hwinfo_freq_min_ = 0;
double hwinfo_freq_max_ = 0;
double hwinfo_gain_min_ = 0;
double hwinfo_gain_max_ = 0;
};
} // namespace habdec

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,17 @@
include_directories( ${PROJECT_SOURCE_DIR} )
include_directories( ${CMAKE_CURRENT_SOURCE_DIR} )
set ( FLTK_SKIP_FLUID True )
find_package( FLTK REQUIRED )
include_directories( ${FLTK_INCLUDE_DIR} )
message( "FLTK Include:" ${FLTK_INCLUDE_DIR} )
message( "FLTK Lib:" ${FLTK_LIBRARIES} )
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-variable")
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-unused-parameter")
add_executable (habdec_fltk main.cpp gui_utils.h )
target_link_libraries( habdec_fltk Decoder ${FLTK_LIBRARIES} IQSource Decoder pthread )
install ( TARGETS habdec_fltk DESTINATION ${CMAKE_INSTALL_PREFIX} )

Wyświetl plik

@ -0,0 +1,234 @@
#pragma once
#include <cstring>
#include <cmath>
#include <memory>
#include <iostream>
#include <vector>
#include <algorithm>
#define BG_COLOR 45
#define TICK_COLOR 50
#define CIRC_COLOR 0
typedef uchar LUMA_T;
typedef uchar RGB_T;
extern const int RES_X;
extern const int RES_Y;
extern RGB_T SPECTRUM_BITMAP_RGB [];
extern RGB_T TIME_BITMAP_RGB [];
template<class T>
void SimpleDownsampleVector(std::vector<T>& vec, size_t factor)
{
using namespace std;
if(!vec.size())
return;
if(factor<2)
return;
const size_t _S = vec.size() / factor;
if(factor == 2)
{
for(size_t i=0; i<_S; ++i)
vec[i] = .5 * (vec[2*i] + vec[2*i+1]);
}
else
{ //somehow does not work for ractor=2
for(size_t i=0; i<_S; ++i)
{
for(size_t j=1; j<factor; ++j)
vec[i] += vec[i*factor + j];
vec[i] /= factor;
}
}
vec.resize(_S);
}
void ClearBitmap(LUMA_T* p_bitmap, int x, int y, int s=1)
{
memset( (void*)p_bitmap, BG_COLOR, x*y * s * sizeof(LUMA_T) );
}
template<typename COLOR_T>
void Histogram2Bitmap(COLOR_T* p_bitmap, int spectr_res_x, int spectr_res_y,
//float* p_values, int num_values,
const std::vector<float>& values,
float min_value, float max_value, float avg_value,
float offset, float scale,
bool is_rgb)
{
using namespace std;
if(min_value == max_value)
{
min_value = *min_element( values.begin(), values.end() );
max_value = *max_element( values.begin(), values.end() );
}
//if(fabs(min_value) > 100 || fabs(max_value) > 100) return;
static float total_scale = fabs(max_value - min_value);
//cout<<"total_scale "<<total_scale<<endl;
for(int pix_x=0; pix_x<spectr_res_x; ++pix_x)
{
int i = round( float(pix_x) / (spectr_res_x-1) * (values.size()-1) );
//cout<<i<<" values[i] "<<values[i]<<endl;
// input values are log10, so can be negatives
float val_0_1 = (values[i] - min_value) / total_scale;
val_0_1 = offset + scale * val_0_1;
if(val_0_1 < 0) val_0_1 = 0;
if(val_0_1 > 1) val_0_1 = 1;
int y_tip = val_0_1 * (spectr_res_y-1);
y_tip = spectr_res_y - 1 - y_tip;
int x = pix_x;
for(int y=y_tip; y<spectr_res_y; ++y)
{
//pixel brightness
float _y_0_1 = 1.0f - (float(y) / spectr_res_y);;
float _b = 10.0f * _y_0_1 * val_0_1;
if(_b < 0) _b = 0;
if(_b > 1) _b = 1;
size_t off = y*spectr_res_x+x;
if(is_rgb)
{
off *= 3;
if(pix_x > .5f * spectr_res_x)
{
p_bitmap[off] = (COLOR_T)(_b * 255);
p_bitmap[off+1] = (COLOR_T)(_b * 0);
p_bitmap[off+2] = 0;
}
else
{
p_bitmap[off] = 0;
p_bitmap[off+1] = (COLOR_T)(_b * 155);
p_bitmap[off+2] = (COLOR_T)(_b * 255);
}
}
else
{
p_bitmap[off] = (COLOR_T)(_b * 255);//220;
}
}
}
// center vertical line
for(int y=0; y<spectr_res_y; ++y)
{
size_t off = y*spectr_res_x+spectr_res_x/2;
if(is_rgb)
{
off *= 3;
p_bitmap[off] = (COLOR_T)(110);
p_bitmap[off+1] = (COLOR_T)(110);
p_bitmap[off+2] = 110;
}
else
{
p_bitmap[off] = (COLOR_T)(110);//220;
}
}
}
template<typename COLOR_T, typename TReal>
void VectorToBitmap(COLOR_T* p_bitmap, const std::vector<TReal>& samples_, int m_res_x, int m_res_y)
{
auto abs_sum = [&](TReal a, TReal b){return abs(a) + abs(b);};
const TReal avg = accumulate(samples_.begin(), samples_.end(), .0, abs_sum) / samples_.size();
for(int x=0; x<m_res_x; ++x)
{
TReal _x_0_1 = TReal(x) / m_res_x;
int i = _x_0_1 * samples_.size();
TReal val_rel = samples_[i] / (3*avg);
val_rel = min(max(-1.0f,val_rel), 1.0f);
val_rel = .5 + .5 * val_rel;
int y = (1.0f - val_rel) * m_res_y;
if(y >= m_res_y)
y = m_res_y - 1;
size_t off = y*m_res_x+x;
if(samples_[_x_0_1 * samples_.size()] > 0)
{
p_bitmap[3*off+0] = (RGB_T)(255);
p_bitmap[3*off+1] = (RGB_T)(0);
p_bitmap[3*off+2] = (RGB_T)(0);
}
else
{
p_bitmap[3*off+0] = (RGB_T)(0);
p_bitmap[3*off+1] = (RGB_T)(150);
p_bitmap[3*off+2] = (RGB_T)(255);
}
}
}
template<typename COLOR_T>
void HorizontalLineToBitmap(COLOR_T* p_bitmap, int spectr_res_x, int y, bool is_rgb,
short r=0, short g=200, short b=250)
{
for(int x=0; x<spectr_res_x; ++x)
{
size_t off = y*spectr_res_x+x;
if(is_rgb)
{
off *= 3;
p_bitmap[off] = r;
p_bitmap[off+1] = g;
p_bitmap[off+2] = b;
}
else
{
p_bitmap[off] = (int(r)+g+b)/3;
}
}
}
template<typename COLOR_T>
void VerticalLineToBitmap(COLOR_T* p_bitmap, int spectr_res_x, int spectr_res_y, int x, bool is_rgb,
short r=0, short g=200, short b=250)
{
//int x = peak.first;
for(int y=0; y<spectr_res_y; ++y)
{
size_t off = y*spectr_res_x+x;
if(is_rgb)
{
off *= 3;
p_bitmap[off] = r;
p_bitmap[off+1] = g;
p_bitmap[off+2] = b;
}
else
{
p_bitmap[off] = (int(r)+g+b)/3;
}
}
}

Wyświetl plik

@ -0,0 +1,426 @@
#include <iostream>
#include <iomanip>
#include <numeric>
using namespace std;
#include <FL/Fl.H>
#include <FL/Fl_Window.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Box.H>
#include <FL/fl_draw.H>
#include <FL/Fl_Value_Slider.H>
#include <FL/Fl_Hor_Value_Slider.H>
#include <FL/Fl_Spinner.H>
#include <FL/Fl_Group.H>
#include <FL/Fl_Pack.H>
#include <FL/Fl_Roller.H>
#include <FL/Fl_Value_Input.H>
#include <FL/Fl_Button.H>
#include <FL/names.h>
#include "IQSource/IQSource_File.h"
#include "IQSource/IQSource_SoapySDR.h"
#include "Decoder/Decoder.h"
#include "gui_utils.h"
using namespace std;
using namespace habdec;
typedef float TReal;
IQVector<TReal> G_SAMPLES;
Decoder<TReal> G_DECODER;
IQSource* G_IQ_SRC_PTR = 0;
double G_FREQ = 100e6; // 434.274451e6;
double G_SAMPLING_RATE = 0;
double G_FREQ_SPAN = 0;
bool DO_CORRECTION = false;
void SetFrequency(double freq)
{
if(G_IQ_SRC_PTR)
{
G_FREQ = freq;
double freq_double = freq;
G_IQ_SRC_PTR->setOption("frequency_double", &freq_double);
}
}
void RunDecoder()
{
size_t max_samples_num = 256*256; // it doesn't work for small batches and radio ...
G_SAMPLES.resize(max_samples_num);
while(1)
{
typedef std::chrono::nanoseconds TDur;
auto _start = std::chrono::high_resolution_clock::now();
size_t count = G_IQ_SRC_PTR->get( G_SAMPLES.data(), G_SAMPLES.size() );
G_DECODER.pushSamples(G_SAMPLES);
G_DECODER();
TDur _duration = std::chrono::duration_cast<TDur>(std::chrono::high_resolution_clock::now() - _start);
// std::cout<<"Decoder duration "<<_duration.count()<<" nS "<<int(double(10e9)/_duration.count())<<" / second\n";
static auto last_afc_time = std::chrono::high_resolution_clock::now();
if( std::chrono::duration_cast< std::chrono::microseconds >
(std::chrono::high_resolution_clock::now() - last_afc_time).count() > 1000000
)
{
double freq_corr = G_DECODER.getFrequencyCorrection();
if(DO_CORRECTION)
{
if( 100 < abs(freq_corr) )
{
G_FREQ += freq_corr;
G_IQ_SRC_PTR->setOption("frequency_double", &G_FREQ);
G_DECODER.resetFrequencyCorrection(freq_corr);
last_afc_time = std::chrono::high_resolution_clock::now();
}
}
}
}
}
int InitProcess(int baud, int a_bits, int a_stops, std::string fname)
{
if(fname != "")
{
cout<<"File"<<endl;
G_SAMPLING_RATE = 10027008 / 256;
G_SAMPLES.samplingRate(G_SAMPLING_RATE);
G_IQ_SRC_PTR = new IQSource_File<TReal>;
G_IQ_SRC_PTR->setOption("sampling_rate_double", &G_SAMPLING_RATE);
G_IQ_SRC_PTR->setOption("file_string", &fname);
bool realtime = false;
G_IQ_SRC_PTR->setOption("realtime_bool", &realtime);
bool loop = true;
G_IQ_SRC_PTR->setOption("loop_bool", &loop);
if( !G_IQ_SRC_PTR->init() )
{
cout<<"IQSource_File::init failed."<<endl;
return 1;
}
cout<<"IQSource_File::count: "<<G_IQ_SRC_PTR->count()<<endl;
}
else
{
cout<<"RADIO"<<endl;
// size_t max_samples_num = 256 * 256; // it doesn't work for small batches...
// G_SAMPLES.resize(max_samples_num);
SoapySDR::KwargsList device_list = SoapySDR::Device::enumerate();
if(!device_list.size())
{
cout<<"No SoapySDR devices found. Exit."<<endl;
return 0;
}
auto& device = device_list.back();
G_IQ_SRC_PTR = new IQSource_SoapySDR;
G_IQ_SRC_PTR->setOption("SoapySDR_Kwargs", &device);
if( !G_IQ_SRC_PTR->init() )
{
cout<<"IQSource_SoapySDR::init failed."<<endl;
return 1;
}
double sr;
G_IQ_SRC_PTR->getOption("sampling_rate_double", &sr);
cout<<C_RED<<"SETTING SR "<<sr<<C_OFF<<endl;
G_SAMPLES.samplingRate(sr);
const double gain = 15;
G_IQ_SRC_PTR->setOption("gain_double", &gain);
G_FREQ = 434.274e6;
SetFrequency(G_FREQ); // RTL
}
cout<<"G_IQ_SRC_PTR->sampling_rate() "<<G_IQ_SRC_PTR->samplingRate()<<endl;
if( !G_IQ_SRC_PTR->start() )
{
cout<<"IQSource_File::start failed."<<endl;
return 1;
}
if( !G_IQ_SRC_PTR->isRunning() )
{
cout<<"IQSource_File::isRunning failed."<<endl;
return 1;
}
// DECODER
G_DECODER.baud(baud);
G_DECODER.rtty_bits(a_bits);
G_DECODER.rtty_stops(a_stops);
G_DECODER.livePrint(true);
// std::this_thread::sleep_for( std::chrono::duration<double, std::milli>(1000) );
std::thread* p_thread = new std::thread(RunDecoder);
return 0;
}
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
typedef uchar LUMA_T;
typedef uchar RGB_T;
#define BG_COLOR 45
const int RES_X = 1024;
const int RES_Y = 256;
RGB_T SPECTRUM_BITMAP_RGB [RES_X*RES_Y*3]; // FFT
RGB_T TIME_BITMAP_RGB [RES_X*RES_Y*3]; // Demodulated samples
class FreqViewport : public Fl_Box
{
public:
FreqViewport(int X,int Y,int W,int H, const char*L=0)
: Fl_Box(X,Y,W,H,L), m_x(X), m_y(Y), m_res_x(W), m_res_y(H)
{
box(FL_FLAT_BOX);
color(BG_COLOR);
Fl::add_timeout(0.1, FreqViewport_CB, (void*)this);
}
private:
const int m_x;
const int m_y;
const int m_res_x;
const int m_res_y;
// frequency drag
int m_xMB;
bool m_DRAG;
int m_xMB_x;
int m_drag_freq_start;
// IQVector<TReal> m_frequencies_;
std::vector<TReal> m_magnitudesArr;
int handle(int event)
{
if(event == FL_MOUSEWHEEL)
{
size_t decimation_factor = G_DECODER.getDecimationFactor();
size_t new_decim_exp = log2(decimation_factor) - Fl::event_dy();
cout<<"Decimation: "<<pow(2,new_decim_exp)<<endl;
G_DECODER.setupDecimationStagesFactor(pow(2,new_decim_exp));
return 1;
}
if(event ==FL_PUSH)
{
m_xMB = Fl::event_button();
m_xMB_x = Fl::event_x();
m_drag_freq_start = G_FREQ;
return 1;
}
if(event == FL_RELEASE)
{
m_xMB = 0;
return 1;
}
if(m_xMB && event == FL_DRAG)
{
double _dx_0_1 = double(Fl::event_x()-m_xMB_x) / w();
double freq_change = _dx_0_1 * G_DECODER.getDecimatedSamplingRate();
if(m_xMB != FL_LEFT_MOUSE)
freq_change *= 0.1;
double _f_new = double(m_drag_freq_start) - freq_change;
cout<<_f_new<<endl;
SetFrequency(_f_new);
return 1;
}
return 0;
}
void draw()
{
SpectrumInfo<TReal> spectr_inf = G_DECODER.getSpectrumInfo();
if(!spectr_inf.size())
return;
m_magnitudesArr = spectr_inf;
if( !m_magnitudesArr.size() )
{
cout<<"if( !m_magnitudesArr.size() )"<<endl;
return;
}
const double resize = double(m_res_x) / spectr_inf.size();
int pl = resize * spectr_inf.peak_left_ ;
int pr = resize * spectr_inf.peak_right_;
double nf = spectr_inf.noise_floor_;
double nv = spectr_inf.noise_variance_;
SimpleDownsampleVector(m_magnitudesArr, 1.0/resize);
static Average<double> low_level(25, spectr_inf.min_);
low_level.add(spectr_inf.min_);
// double low_level = -300;
nf = (nf > (double)low_level) ? nf : (double)low_level;
ClearBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, 3);
Histogram2Bitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y,
m_magnitudesArr,
low_level, 0, 0,
.0, .99, true);
if(spectr_inf.peak_left_valid_)
VerticalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, pl, true, 200, 50, 0);
else
VerticalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, pl, true, 50, 12, 0);
if(spectr_inf.peak_right_valid_)
VerticalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, pr, true, 0, 80, 250);
else
VerticalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, m_res_y, pr, true, 0, 20, 60);
HorizontalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, (nf/low_level)*m_res_y, true, 80,80,80);
HorizontalLineToBitmap(SPECTRUM_BITMAP_RGB, m_res_x, ((nf+nv)/low_level)*m_res_y, true, 80,80,80);
Fl_Box::draw();
fl_draw_image(SPECTRUM_BITMAP_RGB, m_x, m_y, m_res_x, m_res_y, 3, 0);
}
static void FreqViewport_CB(void *userdata)
{
((FreqViewport*)userdata)->redraw();
Fl::repeat_timeout(1.0f/500, FreqViewport_CB, userdata);
}
};
class DemodViewport : public Fl_Box
{
public:
const int m_x;
const int m_y;
const int m_res_x;
const int m_res_y;
DemodViewport(int X,int Y,int W,int H, const char*L=0)
: Fl_Box(X,Y,W,H,L), m_x(X), m_y(Y), m_res_x(W), m_res_y(H)
{
box(FL_FLAT_BOX);
color(BG_COLOR);
Fl::add_timeout(0.1, DemodViewport_CB, (void*)this);
}
private:
std::vector<TReal> samples_;
size_t samples_to_show_cnt_ = 0;
void draw()
{
if(!samples_to_show_cnt_)
samples_to_show_cnt_ = G_DECODER.getDecimatedSamplingRate() / G_DECODER.getSymbolRate() * 10; // 10 symbols
const size_t samples_size_pre_insert_ = samples_.size();
auto demod = G_DECODER.getDemodulated();
samples_.insert(
samples_.end(),
demod.cbegin(),
demod.cbegin() + min(samples_to_show_cnt_,demod.size())
);
// if(!samples_.size())
if(samples_.size() < samples_to_show_cnt_)
return;
ClearBitmap(TIME_BITMAP_RGB, m_res_x, m_res_y, 3);
VectorToBitmap(TIME_BITMAP_RGB, samples_, m_res_x, m_res_y);
HorizontalLineToBitmap(TIME_BITMAP_RGB, m_res_x, m_res_y/2, true);
Fl_Box::draw();
fl_draw_image(TIME_BITMAP_RGB, m_x, m_y, m_res_x, m_res_y, 3, 0);
if(samples_.size() > samples_to_show_cnt_)
samples_.erase( samples_.begin(), samples_.end()-samples_size_pre_insert_);
}
static void DemodViewport_CB(void *userdata)
{
((DemodViewport*)userdata)->redraw();
Fl::repeat_timeout(1.0f/10, DemodViewport_CB, userdata);
}
};
/////////////////////////////////
/////////////////////////////////
void DO_AFC_CB(Fl_Widget* p_w, void* p_user)
{
DO_CORRECTION = !DO_CORRECTION;
}
int GUI_MAIN()
{
Fl::visual(FL_RGB); // disable dithering
Fl_Double_Window* p_window = new Fl_Double_Window(RES_X, 1.5*RES_Y + 50);
p_window->begin();
FreqViewport* p_freqVP = new FreqViewport( 0, 0*RES_Y, RES_X, RES_Y);
DemodViewport* p_timeVP = new DemodViewport( 0, 1*RES_Y, RES_X, RES_Y/2);
auto button = new Fl_Button(0, 1*RES_Y + RES_Y/2 + 10, 100, 20, "AFC");
button->callback( ( Fl_Callback* ) DO_AFC_CB );
p_window->end();
p_window->show(0, 0);
return Fl::run();
}
int main(int argc, char** argv)
{
using namespace std;
struct thousand_separators : numpunct<char> {
char do_thousands_sep() const { return ','; }
string do_grouping() const { return "\3"; }
};
cout.imbue( locale(locale(""), new thousand_separators) );
string file("");
if(argc > 4)
file = string(argv[4]);
cout<<"File: "<<file<<endl;
InitProcess( std::stoi(argv[1]), std::stoi(argv[2]), std::stoi(argv[3]), file);
GUI_MAIN();
// while(1) this_thread::sleep_for(chrono::duration<double, milli>(3000));
}

Wyświetl plik

@ -0,0 +1,149 @@
#!/usr/bin/env python
import string
import os
import sys
import time
import datetime
import argparse
import json
import re
import traceback
from base64 import b64encode
import httplib
from hashlib import sha256
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"
# logname = time.strftime("%Y-%m-%d_%H.%M.%S", time.gmtime()) + ".txt"
logname = time.strftime("%Y-%m-%d_%H", time.gmtime()) + ".txt"
with open('./' + logname, 'a') as f:
f.write(logname + "\n")
def prog_opts():
parser = argparse.ArgumentParser(description='arg parser')
parser.add_argument('--addr', dest='port', action='store', help='port')
parser.add_argument('--station',dest='station', action='store', help='listener callsign')
args = parser.parse_args()
return args
def get_config():
opts = prog_opts()
CFG = {}
CFG['addr'] = ""
CFG['station'] = ""
if opts.port: CFG['addr'] = opts.port
if opts.station: CFG['station'] = opts.station
return CFG
def crc(i_str):
def _hex(Character):
_hexTable = '0123456789ABCDEF'
return _hexTable[Character]
CRC = 0xffff
xPolynomial = 0x1021
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
def AppendToLogFile(msg):
with open('./' + logname, 'a') as f:
msg = string.strip(msg)
f.write(msg + '\n\r')
def sendSentence(sntc, listener_callsign):
# print ("PYTHON ", sntc, listener_callsign)
# return
sentence = sntc
if sentence[-1] != '\n': sentence += '\n'
if sentence[0] != '$': sentence = '$' + sentence
if sentence[1] != '$': sentence = '$' + sentence
print "PY SENTENCE ", sentence
sentence = b64encode(sentence)
retries = 5
while retries:
date = datetime.datetime.utcnow().isoformat("T") + "Z"
data = {
"type": "payload_telemetry",
"data": {
"_raw": sentence
},
"receivers": {
listener_callsign: {
"time_created": date,
"time_uploaded": date,
},
},
}
c = httplib.HTTPConnection("habitat.habhub.org")
c.request(
"PUT",
"/habitat/_design/payload_telemetry/_update/add_listener/%s" % sha256(sentence).hexdigest(),
json.dumps(data), # BODY
{"Content-Type": "application/json"} # HEADERS
)
response = c.getresponse()
print response.status, response.reason, response.read()
if response.status == 201 or response.status == '201':
retries == 0
break
retries = retries - 1
time.sleep(1)
def main():
caller = "habdec"
if len(sys.argv) > 2:
caller = sys.argv[2]
if len(sys.argv) > 1:
sendSentence(sys.argv[1], caller)
if __name__ == '__main__':
try:
main()
except:
print traceback.format_exc()

Wyświetl plik

@ -0,0 +1,74 @@
body, html {
background-color:hsl(210, 15%, 24%);
}
div{
font-family: Tahoma, Verdana, Segoe, sans-serif;
}
label {
color: hsl(32, 93%, 45%);
}
button {
background-color:hsl(210, 15%, 34%);
border: none;
color: #AAAAAA;
/* padding: 15px 32px; */
text-align: center;
display: inline-block;
font-size: 20px;
height: 4.0rem;
border: 0.1rem solid hsl(210, 15%, 20%);
border-radius: .4rem;
}
input[type=checkbox]
{
/* Double-sized Checkboxes */
-ms-transform: scale(2.5); /* IE */
-moz-transform: scale(2.5); /* FF */
-webkit-transform: scale(2.5); /* Safari and Chrome */
-o-transform: scale(2.5); /* Opera */
padding: 10px;
}
.checkboxtext
{
font-size: 130%;
display: inline;
}
.ctrl_container {
width: 100%;
}
.habsentence_text {
font-size: 12px;
}
.ctrl_box {
color: hsl(32, 93%, 60%);
background-color: transparent;
border: 0.1rem solid #000000;
border-radius: .4rem;
height: 2.5rem;
padding: .6rem 1.0rem;
width: 50px;
}
.increment_button {
background-color:hsl(210, 15%, 34%);
border: none;
color: #AAAAAA;
text-align: center;
display: inline-block;
font-size: 20px;
height: 60px;
width: 80px;
border: 0.1rem solid hsl(210, 15%, 20%);
border-radius: .4rem;
}

Wyświetl plik

@ -0,0 +1,94 @@
<!DOCTYPE html>
<meta charset="utf-8" />
<script src="js/NetTransport.js"></script>
<script src="js/habdec_commands.js"></script>
<script src="js/drawing.js"></script>
<script src="js/gui.js"></script>
<head>
<style>
body, html {
height: 100%;
width: 100%;
}
div {
font-family: Tahoma, Verdana, Segoe, sans-serif;
}
</style>
<link rel="stylesheet" href="css/habdec.css">
</head>
<body>
<!-- Power Spectrum -->
<div style="display: grid; grid-template-columns: auto 80px; width: 100%; height: 150px;" >
<div id="cnt_powerSpectrumCanvas" style="display: flex;">
<canvas id="powerSpectrumCanvas" ></canvas>
</div>
<div>
<button type="button" style="height: 50%; width: 100%; overflow: auto; font-size: 30px;" onclick="(function(){G_SPECTRUM_ZOOM += .1})()" > + </button><br>
<button type="button" style="height: 50%; width: 100%; overflow: auto; font-size: 30px;" onclick="(function(){G_SPECTRUM_ZOOM -= .1})()" > - </button><br>
</div>
</div>
<div style="display: grid; grid-template-columns: auto 540px; width: 100%;" >
<!-- Demod Graph -->
<div>
<div id="cnt_demodCanvas" style="display: flex; height: 128px;">
<canvas id="demodCanvas" height="128px"></canvas>
</div>
<div>
<div id="cnt_debug" style="font-size: 12px;"></div>
<!-- <div id="cnt_habsentence" class="habsentence">SENTENCE</div> -->
<br>
<div id="cnt_liveprint" class="habsentence_text" style="color: cadetblue"></div>
<div id="cnt_habsentence_count" class="habsentence_text" style="color: rgb(122, 52, 163)"></div>
<div id="cnt_habsentence_list" class="habsentence_text"></div>
</div>
</div>
<!-- Control Buttons -->
<div>
<div id="cnt_spectrum_zoom" class="ctrl_container"> </div>
<div id="cnt_frequency" class="ctrl_container"> </div>
<div id="cnt_decimation" class="ctrl_container"> </div>
<div id="cnt_gain" class="ctrl_container"> </div>
<div id="cnt_lowpass_bw" class="ctrl_container"> </div>
<div id="cnt_lowpass_trans" class="ctrl_container"> </div>
<div id="cnt_baud" class="ctrl_container"> </div>
<div id="cnt_rtty_bits" class="ctrl_container"> </div>
<div id="cnt_rtty_stops" class="ctrl_container"> </div>
<div id="cnt_datasize" class="ctrl_container"> </div>
</div>
</div>
<div>
<input type="checkbox" id="biastee" oninput="SetBiasT()"> <span class="checkboxtext">BiasTee</span> <br> <br>
<input type="checkbox" id="afc" oninput="SetAFC()"> <span class="checkboxtext">AFC</span>
<p> <button id="btnFullscreen" type="button" onclick="toggleFullscreen()">Fullscreen</button> </p>
</div>
<div>
<div><label>Server Address</label></div>
<input id="server_address" value="127.0.0.1:5555">
<button onclick="OpenConnection()" >Connect</button>
</div>
</body>
<script language="javascript" type="text/javascript">
function habdec_init()
{
OpenConnection();
CreateControls();
ResizeCanvas("powerSpectrumCanvas");
ResizeCanvas("demodCanvas");
}
window.addEventListener("load", habdec_init, false);
</script>

Wyświetl plik

@ -0,0 +1,80 @@
function DecodeSpectrum(i_buffer, i_offset)
{
var header =
{
header_size_ : 0, // int32_t
noise_floor_ : 0, // float
noise_variance_ : 0, // float
sampling_rate_: 0, // float
shift_ : 0, // float
peak_left_ : 0, // int32_t
peak_right_ : 0, // int32_t
peak_left_valid_ : 0, // int32_t
peak_right_valid_ : 0, // int32_t
min_ : 0, // float
max_ : 0, // float
type_size_ : 0, // int32_t. value:s 1/2/4 for uint8 uint16 float32
size_ : 0 // int32_t
};
var dv = new DataView(i_buffer, i_offset);
var offset = 0;
header.header_size_ = dv.getInt32 (offset, true); offset += 4;
header.noise_floor_ = dv.getFloat32 (offset, true); offset += 4;
header.noise_variance_ = dv.getFloat32 (offset, true); offset += 4;
header.sampling_rate_= dv.getFloat32 (offset, true); offset += 4;
header.shift_ = dv.getFloat32 (offset, true); offset += 4;
header.peak_left_ = dv.getInt32 (offset, true); offset += 4;
header.peak_right_ = dv.getInt32 (offset, true); offset += 4;
header.peak_left_valid_= dv.getInt32 (offset, true); offset += 4;
header.peak_right_valid_= dv.getInt32 (offset, true); offset += 4;
header.min_ = dv.getFloat32 (offset, true); offset += 4;
header.max_ = dv.getFloat32 (offset, true); offset += 4;
header.type_size_ = dv.getInt32 (offset, true); offset += 4;
header.size_ = dv.getInt32 (offset, true); offset += 4;
// add data
if(header.type_size_ == 1) // 8 bit char
header.values_ = new Uint8Array( i_buffer, offset, header.size_);
else if(header.type_size_ == 2) // uint16_t
header.values_ = new Uint16Array( i_buffer, offset, header.size_);
else if(header.type_size_ == 4) // 32float
header.values_ = new Float32Array( i_buffer, offset, header.size_);
return header;
}
function DecodeDemod(i_buffer, i_offset)
{
var header =
{
header_size_ : 0, // int32_t
min_ : 0, // float
max_ : 0, // float
type_size_ : 0, // int32_t. value:s 1/2/4 for uint8 uint16 float32
size_ : 0 // int32_t
};
var dv = new DataView(i_buffer, i_offset);
var offset = 0;
header.header_size_ = dv.getInt32 (offset, true); offset += 4;
header.min_ = dv.getFloat32 (offset, true); offset += 4;
header.max_ = dv.getFloat32 (offset, true); offset += 4;
header.type_size_ = dv.getInt32 (offset, true); offset += 4;
header.size_ = dv.getInt32 (offset, true); offset += 4;
// add data
if(header.type_size_ == 1) // 8 bit char
header.values_ = new Uint8Array( i_buffer, offset, header.size_);
else if(header.type_size_ == 2) // uint16_t
header.values_ = new Uint16Array( i_buffer, offset, header.size_);
else if(header.type_size_ == 4) // 32float
header.values_ = new Float32Array( i_buffer, offset, header.size_);
return header;
}

Wyświetl plik

@ -0,0 +1,194 @@
function DrawPowerSpectrum(i_canvas, i_spectrum)
{
var ctx = i_canvas.getContext("2d");
// CLEAR THE CANVAS
//
ctx.clearRect(0, 0, i_canvas.width-1, i_canvas.height-1);
// BG
//
var grd_bg = ctx.createLinearGradient(0, 0, 0, i_canvas.height-1);
grd_bg.addColorStop(0, "hsl(210, 15%, 24%)");
grd_bg.addColorStop(.5, "hsl(210, 15%, 40%)");
grd_bg.addColorStop(1, "hsl(210, 15%, 24%)");
ctx.fillStyle = grd_bg;
ctx.fillRect(0, 0, i_canvas.width-1, i_canvas.height-1);
G_SPECTRUM_ZOOM = Math.max(0, Math.min(1, G_SPECTRUM_ZOOM));
var zoom = G_SPECTRUM_ZOOM;
// LOWPASS FILTER DRAW
//
var _lowpass_bw = GLOBALS.lowpass_bw / (1.0 - .999*zoom);
var _lowpass_trans = GLOBALS.lowpass_trans / (1.0 - .999*zoom);
var grd_lowpass = ctx.createLinearGradient(0, 0, i_canvas.width-1, 0);
var _l = Math.max(0, .5 - .5 * _lowpass_bw);
var _ll = Math.max(0, .5 - .5 * (_lowpass_bw + _lowpass_trans));
var _r = Math.min(1, .5 + .5 * _lowpass_bw);
var _rr = Math.min(1, .5 + .5 * (_lowpass_bw + _lowpass_trans));
grd_lowpass.addColorStop(0, "rgba(15,25,50,0)");
grd_lowpass.addColorStop(_ll, "rgba(15,25,50,0)");
grd_lowpass.addColorStop(_l, "#113555");
grd_lowpass.addColorStop(_r, "#113555");
grd_lowpass.addColorStop(_rr, "rgba(15,25,50,0)");
grd_lowpass.addColorStop(1, "rgba(15,25,50,0)");
ctx.fillStyle = grd_lowpass;
ctx.fillRect(0, 0, i_canvas.width-1, i_canvas.height-1);
// SPECTRUM
//
var power_grd = ctx.createLinearGradient(0, 0, 0, i_canvas.height-1);
power_grd.addColorStop(0.2, "yellow");
power_grd.addColorStop(.6, "#993311");
power_grd.addColorStop(1, "black");
ctx.strokeStyle = power_grd;
ctx.beginPath();
if(i_spectrum.type_size_ == 1) // 8 bit char
{
for(var x=0; x<i_canvas.width; ++x)
{
var x_0_1 = x/(i_canvas.width-1);
var val_0_1 = i_spectrum.values_[ Math.round(x_0_1 * i_spectrum.values_.length) ] / 255;
var val_pixel = (1-val_0_1) * (i_canvas.height-1);
ctx.moveTo(x, i_canvas.height - 1);
ctx.lineTo(x, val_pixel);
}
}
else if(i_spectrum.type_size_ == 2) // uint16_t
{
for(var x=0; x<i_canvas.width; ++x)
{
var x_0_1 = x/(i_canvas.width-1);
var val_0_1 = i_spectrum.values_[ Math.round(x_0_1 * i_spectrum.values_.length) ] / 65535;
var val_pixel = (1-val_0_1) * (i_canvas.height-1);
ctx.moveTo(x, i_canvas.height - 1);
ctx.lineTo(x, val_pixel);
}
}
else if(i_spectrum.type_size_ == 4) // 32float
{
for(var x=0; x<i_canvas.width; ++x)
{
var x_0_1 = x/(i_canvas.width-1);
var val_0_1 = (i_spectrum.values_[Math.round(x_0_1 * i_spectrum.values_.length)] - i_spectrum.min_) / (i_spectrum.max_ - i_spectrum.min_) ;
var val_pixel = (1-val_0_1) * (i_canvas.height-1);
ctx.moveTo(x, i_canvas.height - 1);
ctx.lineTo(x, val_pixel);
}
}
ctx.stroke();
// CENTER LINE
//
ctx.strokeStyle = '#888888';
ctx.beginPath();
ctx.moveTo(i_canvas.width/2, i_canvas.height - 1);
ctx.lineTo(i_canvas.width/2, 0);
ctx.stroke();
// NOISE FLOOR
//
ctx.strokeStyle = '#333388';
ctx.beginPath();
var nf_0_1 = (i_spectrum.noise_floor_ - i_spectrum.min_) / (i_spectrum.max_ - i_spectrum.min_);
ctx.moveTo(0, (1-nf_0_1)*i_canvas.height - 1);
ctx.lineTo(i_canvas.width-1, (1-nf_0_1)*i_canvas.height - 1);
ctx.stroke();
// PEAK LEFT
//
if(i_spectrum.peak_left_valid_)
ctx.strokeStyle = '#FF5500';
else
ctx.strokeStyle = '#55000';
ctx.beginPath();
var peak_left_0_1 = i_spectrum.peak_left_ / i_spectrum.size_;
ctx.moveTo(peak_left_0_1 * i_canvas.width, 0);
ctx.lineTo(peak_left_0_1 * i_canvas.width, i_canvas.height - 1);
ctx.stroke();
// PEAK RIGHT
//
if(i_spectrum.peak_right_valid_)
ctx.strokeStyle = '#0088FF';
else
ctx.strokeStyle = '#000055';
ctx.beginPath();
var peak_right_0_1 = i_spectrum.peak_right_ / i_spectrum.size_;
ctx.moveTo(peak_right_0_1 * i_canvas.width, 0);
ctx.lineTo(peak_right_0_1 * i_canvas.width, i_canvas.height - 1);
ctx.stroke();
}
function DrawDemod(i_canvas, i_demod)
{
var ctx = i_canvas.getContext("2d");
// Clear the canvas
ctx.clearRect(0, 0, i_canvas.width, i_canvas.height);
// BG
//
var grd_bg = ctx.createLinearGradient(0, 0, 0, i_canvas.height-1);
grd_bg.addColorStop(0, "hsl(210, 15%, 24%)");
grd_bg.addColorStop(.5,"hsl(210, 15%, 40%)");
grd_bg.addColorStop(1, "hsl(210, 15%, 24%)");
ctx.fillStyle = grd_bg;
ctx.fillRect(0, 0, i_canvas.width-1, i_canvas.height-1);
// CENTER LINE
//
ctx.strokeStyle = 'hsl(210, 15%, 30%)';
ctx.beginPath();
ctx.moveTo(0, i_canvas.height/2);
ctx.lineTo(i_canvas.width-1, i_canvas.height/2);
ctx.stroke();
// DEMOD
//
ctx.strokeStyle = "#aa5500";
ctx.beginPath();
ctx.moveTo(0, 0);
for(var x=0; x<i_canvas.width; ++x)
{
var x_0_1 = x/(i_canvas.width-1);
var raw_value = i_demod.values_[ Math.round(x_0_1 * i_demod.values_.length) ];
var full_scale_value = 0;
if(i_demod.type_size_ == 1) // 8 bit char
full_scale_value = i_demod.min_ + raw_value / 255.0 * (i_demod.max_ - i_demod.min_);
else if(i_demod.type_size_ == 2) // uint16_t
full_scale_value = i_demod.min_ + raw_value / 65535.0 * (i_demod.max_ - i_demod.min_);
else if(i_demod.type_size_ == 4) // 32float
full_scale_value = raw_value;
full_scale_value *= .75; // scale down a little bit
var val_0_1 = .5 + .5 * full_scale_value / Math.max( Math.abs( i_demod.min_ ), Math.abs( i_demod.max_ ) );
var val_pixel = (1.0-val_0_1) * (i_canvas.height-1);
ctx.lineTo(x, val_pixel);
}
ctx.stroke();
}
function ResizeCanvas(canvas_id)
{
var canvasNode = document.getElementById(canvas_id);
var canvasDiv = canvasNode.parentNode;
canvasNode.style.width = '100%';
canvasNode.style.height = '100%';
canvasNode.width = canvasDiv.clientWidth;
canvasNode.height = canvasDiv.clientHeight;
}

Wyświetl plik

@ -0,0 +1,155 @@
function CreateFloatBoxWithArrows( i_cnt, i_parameter, i_callback,
i_min, i_max, i_default, step_small = 0, step_big = 0, step_box = 0)
{
var widget = document.createElement("INPUT");
widget.classList.add('ctrl_box');
widget.setAttribute("id", i_parameter);
widget.setAttribute("type", "number");
widget.setAttribute("name", i_parameter);
widget.setAttribute("min", i_min);
widget.setAttribute("max", i_max);
widget.setAttribute("defaultValue", i_default);
widget.value = i_default;
widget.onchange = function() {
i_callback("set:" + i_parameter + "=" + widget.value) };
// label
var lab = document.createElement("LABEL");
lab.appendChild( document.createTextNode(i_parameter) );
// determine step size. big and small
if(!step_small)
{
step_small = (i_max - i_min) / 50.0;
step_big = (i_max - i_min) / 5.0;
}
else if(!step_big)
{
step_big = (i_max - i_min) / 5.0;
}
if(!step_box)
step_box = step_small;
widget.setAttribute("step_big", step_big);
widget.setAttribute("step_small", step_small);
widget.setAttribute("step", step_box);
// arrows
var decr_big = document.createElement("button");
decr_big.classList.add("increment_button");
decr_big.appendChild(document.createTextNode("<<<"));
var decr_small = document.createElement("button");
decr_small.classList.add("increment_button");
decr_small.appendChild(document.createTextNode("<"));
var incr_small = document.createElement("button");
incr_small.classList.add("increment_button");
incr_small.appendChild(document.createTextNode(">"));
var incr_big = document.createElement("button");
incr_big.classList.add("increment_button");
incr_big.appendChild(document.createTextNode(">>>"));
// arrows callbacks
decr_big.onclick = function() {
widget.value = parseFloat(widget.value) - parseFloat(widget.getAttribute("step_big"));
i_callback("set:" + i_parameter + "=" + widget.value);
};
decr_small.onclick = function() {
widget.value = parseFloat(widget.value) - parseFloat(widget.getAttribute("step_small"));
i_callback("set:" + i_parameter + "=" + widget.value);
};
incr_small.onclick = function() {
widget.value = parseFloat(widget.value) + parseFloat(widget.getAttribute("step_small"));
i_callback("set:" + i_parameter + "=" + widget.value);
};
incr_big.onclick = function() {
widget.value = parseFloat(widget.value) + parseFloat(widget.getAttribute("step_big"));
i_callback("set:" + i_parameter + "=" + widget.value);
};
document.getElementById(i_cnt).style.textAlign = "right";
document.getElementById(i_cnt).appendChild(lab);
document.getElementById(i_cnt).appendChild(widget);
document.getElementById(i_cnt).appendChild(decr_big);
document.getElementById(i_cnt).appendChild(decr_small);
document.getElementById(i_cnt).appendChild(incr_small);
document.getElementById(i_cnt).appendChild(incr_big);
return widget;
}
function SetGuiToGlobals(i_globals)
{
for(var param in i_globals)
{
var value = i_globals[param];
// console.debug("setting ", param, value);
try {document.getElementById(param).value = value; } catch(err) {};
try {document.getElementById(param + "_box").value = value; } catch(err) {};
try {document.getElementById(param).checked = value; } catch(err) {};
}
}
function CreateControls()
{
var freq_widget = CreateFloatBoxWithArrows("cnt_frequency", "frequency",
SendCommand, 25, 1200, 434.355, 20.0/1e6, 1000.0/1e6, 1e-6);
freq_widget.style.width = "100px";
CreateFloatBoxWithArrows("cnt_decimation", "decimation",
SendCommand, 0, 8, 8, 1, 1);
CreateFloatBoxWithArrows("cnt_gain", "gain",
SendCommand, 0, 49, 21, 1, 5);
CreateFloatBoxWithArrows("cnt_lowpass_bw", "lowpass_bw",
SendCommand, .0, 1.0, .05, .002, .02);
CreateFloatBoxWithArrows("cnt_lowpass_trans", "lowpass_trans",
SendCommand, .0025, 0.1, .05, .0025, .01);
CreateFloatBoxWithArrows("cnt_baud", "baud",
SendCommand, 50, 1200, 300, 25, 100);
CreateFloatBoxWithArrows("cnt_rtty_bits", "rtty_bits",
SendCommand, 7, 8, 8, 1, 1);
CreateFloatBoxWithArrows("cnt_rtty_stops", "rtty_stops",
SendCommand, 1, 2, 2, 1, 1);
CreateFloatBoxWithArrows("cnt_datasize", "datasize",
SendCommand, 1, 4, 1, 1, 1);
}
function toggleFullscreen(elem)
{
elem = elem || document.documentElement;
if (!document.fullscreenElement && !document.mozFullScreenElement &&
!document.webkitFullscreenElement && !document.msFullscreenElement)
{
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
elem.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
}
else
{
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
}
}

Wyświetl plik

@ -0,0 +1,285 @@
var websocket;
var connected = 0;
var LastHabSentences = [];
var G_SPECTRUM_ZOOM = 0;
var G_SENTECES_OK_COUNT = 0;
var GLOBALS =
{
frequency: 0,
sampling_rate: 0,
gain: 0,
baud: 0,
rtty_bits: 0,
rtty_stops: 0,
lowpass_bw: 0,
lowpass_trans: 0,
biastee: 0,
decimation: 0,
afc: 0
};
function debug_print()
{
console.debug(arguments);
/*
document.getElementById("cnt_debug").innerHTML = "";
for (i = 0; i < arguments.length; i++)
document.getElementById("cnt_debug").innerHTML += arguments[i] + " ";
*/
}
function OpenConnection()
{
if(connected)
return;
var server = document.getElementById("server_address").value;
debug_print("Connecting to ", server, " ...");
websocket = new WebSocket("ws://" + server);
websocket.binaryType = 'arraybuffer'; // or 'blob'
websocket.onopen = function(evt) { ws_onOpen(evt) };
websocket.onclose = function(evt) { ws_onClose(evt) };
websocket.onmessage = function(evt) { ws_onMessage(evt) };
websocket.onerror = function(evt) { ws_onError(evt) };
}
function ws_onClose(evt)
{
connected = 0;
debug_print("DISCONNECTED");
setTimeout(function () { OpenConnection(); }, 5000);
}
function ws_onError(evt)
{
debug_print("ws_onError: ", evt.data);
}
function ws_onOpen(evt)
{
connected = 1;
debug_print("ws_onOpen: ", "Connected.");
websocket.send("hi");
for(var param in GLOBALS)
SendCommand("get:" + param);
console.debug("ws_onOpen: init refresh.");
RefreshPowerSpectrum();
RefreshDemod();
RefreshLivePrint();
}
function ws_onMessage(evt)
{
if(!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)
{
var what = String.fromCharCode.apply( null, new Uint8Array(evt.data,0,4) );
if(what == "PWR_")
{
var spectrum = DecodeSpectrum(evt.data, 4);
if(GLOBALS.sampling_rate != spectrum.sampling_rate_)
{
GLOBALS.sampling_rate = spectrum.sampling_rate_;
var widget = document.getElementById("frequency");
widget.setAttribute("step_big", GLOBALS.sampling_rate / 1e6 / 30);
widget.setAttribute("step_small", GLOBALS.sampling_rate / 1e6 / 500);
}
DrawPowerSpectrum(document.getElementById("powerSpectrumCanvas"), spectrum);
}
else if(what == "DEM_")
{
var demod = DecodeDemod(evt.data, 4);
DrawDemod(document.getElementById("demodCanvas"), demod);
}
}
else
{
debug_print("ws_onMessage: unknown data type.");
return;
}
}
function SendCommand(i_cmd)
{
if(!connected)
{
debug_print("SendCommand: not connected.");
return;
}
var msg = "cmd::" + i_cmd;
// debug_print("SendCommand: ", msg);
websocket.send(msg);
}
function HandleMessage(i_data)
{
if(!connected)
{
debug_print("HandleMessage: not connected.");
return;
}
if( !i_data.startsWith("cmd::info:liveprint") )
debug_print("Received Message: ", i_data);
// cmd::set
//
var set_rex = String.raw`cmd\:\:set\:(\D+)=(.+)`;
var set_re = new RegExp(set_rex);
var set_match = set_re.exec(i_data);
if(set_match != null && set_match.length == 3)
{
if(set_match[1] == "frequency")
GLOBALS.frequency = parseFloat(set_match[2]);
if(set_match[1] == "decimation")
GLOBALS.decimation = parseInt(set_match[2]);
else if(set_match[1] == "gain")
GLOBALS.gain = parseFloat(set_match[2]);
else if(set_match[1] == "baud")
GLOBALS.baud = parseInt(set_match[2]);
else if(set_match[1] == "lowpass_bw")
GLOBALS.lowpass_bw = parseFloat(set_match[2]);
else if(set_match[1] == "lowpass_trans")
GLOBALS.lowpass_trans = parseFloat(set_match[2]);
else if(set_match[1] == "rtty_bits")
GLOBALS.rtty_bits = parseFloat(set_match[2]);
else if(set_match[1] == "rtty_stops")
GLOBALS.rtty_stops = parseFloat(set_match[2]);
else if(set_match[1] == "lowPass")
{
GLOBALS.lowpass_bw = parseFloat(set_match[2].split(',')[0]);
GLOBALS.lowpass_trans = parseFloat(set_match[2].split(',')[1]);
}
else if(set_match[1] == "biastee")
{
GLOBALS.biastee = parseFloat(set_match[2]);
debug_print("Received Message: ", i_data);
}
else if(set_match[1] == "afc")
{
GLOBALS.afc = parseFloat(set_match[2]);
debug_print("Received Message: ", i_data);
}
SetGuiToGlobals(GLOBALS);
return true;
}
// cmd::info
//
var data_without_new_lines = i_data.replace(/(\r\n|\n|\r)/gm," ");
var info_rex = String.raw`cmd\:\:info\:(\D+)=(.+)`;
var info_re = new RegExp(info_rex);
var info_match = info_re.exec(data_without_new_lines);
// if (info_match && info_match.length == 3)
{
if(info_match[1] == "sentence")
{
G_SENTECES_OK_COUNT += 1;
document.getElementById("cnt_habsentence_count").innerHTML = "OK: " + G_SENTECES_OK_COUNT;
var sntnc = info_match[2];
var cnt_habsentence_list = document.getElementById("cnt_habsentence_list")
cnt_habsentence_list.innerHTML = '<text style=\"color: rgb(0,200,0);\">' + sntnc + '</text>';;
while(LastHabSentences.length > 12)
LastHabSentences.pop();
LastHabSentences.forEach( function(i_snt){
cnt_habsentence_list.innerHTML += '<br><text>' + i_snt + '</text>';
}
);
LastHabSentences.unshift( info_match[2] );
}
else if(info_match[1] == "liveprint")
{
var livestream = info_match[2];
if(livestream.length > 100)
livestream = livestream.substr(livestream.length-100, livestream.length);
document.getElementById("cnt_liveprint").innerHTML = livestream;
}
return true;
}
return false;
}
function RefreshPowerSpectrum()
{
if(!connected)
return;
G_SPECTRUM_ZOOM = Math.max(0, Math.min(1, G_SPECTRUM_ZOOM));
var zoom = Math.max(0, Math.min(1, G_SPECTRUM_ZOOM));
var canvas = document.getElementById("powerSpectrumCanvas");
SendCommand("power:res=" + canvas.width + ",zoom=" + zoom);
setTimeout(function () {RefreshPowerSpectrum();}, 1000 / 15);
}
function RefreshDemod()
{
if(!connected)
return;
var canvas = document.getElementById("demodCanvas");
SendCommand("demod:res=" + canvas.width);
setTimeout(function () {RefreshDemod();}, 1000 / 3);
}
function RefreshLivePrint()
{
if(!connected)
return;
SendCommand("liveprint");
setTimeout(function () {RefreshLivePrint();}, 1000 / 4);
}
function SetBiasT()
{
var value = document.getElementById("biastee").checked;
if(value)
SendCommand("set:biastee=1");
else
SendCommand("set:biastee=0");
}
function SetAFC()
{
var value = document.getElementById("afc").checked;
if(value)
SendCommand("set:afc=1");
else
SendCommand("set:afc=0");
}

Wyświetl plik

@ -0,0 +1,65 @@
include_directories( ${PROJECT_SOURCE_DIR} )
include_directories( ${CMAKE_CURRENT_SOURCE_DIR} )
set ( FFTW3f_DIR ../CMake )
find_package( FFTW3f REQUIRED )
include_directories( ${FFTW3f_INCLUDE_DIRS} )
# 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 )
include_directories( ${Boost_INCLUDE_DIRS} )
message ( "Boost_INCLUDE_DIRS " ${Boost_INCLUDE_DIRS} )
message ( "Boost_LIBRARY_DIRS " ${Boost_LIBRARY_DIRS} )
find_package(SoapySDR REQUIRED) # this reverts CMAKE_CXX_STANDARD to '11'
#set ( CMAKE_CXX_STANDARD 17 )
include_directories( ${SoapySDR_INCLUDE_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" )
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 ( websocketServer_src
program_options.h program_options.cpp
server.h server.cpp
main.cpp
)
add_executable ( habdecWebsocketServer ${websocketServer_src} )
target_link_libraries( habdecWebsocketServer
Decoder
IQSource
${Boost_LIBRARIES}
${PlatformSpecificLinking} )
install ( TARGETS habdecWebsocketServer 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 ./habdecWebsocketServer --config ./habdecWebsocketServer.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,311 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <vector>
#include <algorithm>
#include <iostream>
namespace habdec
{
template<typename T>
class CompressedVector
{
public:
typedef T TValue;
mutable double min_ = 0;
mutable double max_ = 0;
std::vector<T> values_;
virtual ~CompressedVector() = default;
CompressedVector() = default;
template<typename U>
CompressedVector(const CompressedVector<U>& rhs) :
min_(rhs.min_),
max_(rhs.max_)
// normalized_(rhs.normalized_)
{
copyValues<U>(rhs);
}
template<typename U>
CompressedVector(const std::vector<U>& rhs_vec)
{
min_ = *std::min_element(rhs_vec.begin(), rhs_vec.end());
max_ = *std::max_element(rhs_vec.begin(), rhs_vec.end());
copyValues<U>(rhs_vec, min_, max_);
}
template<typename U>
const CompressedVector<T>& operator=(const CompressedVector<U>& rhs)
{
min_ = rhs.min_;
max_ = rhs.max_;
copyValues<U>(rhs);
return *this;
}
double calcMin() const
{
if(!values_.size())
return 0;
min_ = *std::min_element(values_.begin(), values_.end());
return min_;
}
double calcMax() const
{
if(!values_.size())
return 0;
max_ = *std::max_element(values_.begin(), values_.end());
return max_;
}
private:
template<typename U>
void copyValues(const std::vector<U>& rhs, double i_min, double i_max)
{
if(!rhs.size())
{
values_.clear();
return;
}
values_.resize(rhs.size());
std::copy(rhs.begin(), rhs.end(), values_.begin());
}
};
// specialization: float --> double
template<>
template<>
void CompressedVector<double>::copyValues(const std::vector<float>& rhs, double i_min, double i_max)
{
if(!rhs.size())
{
values_.clear();
return;
}
values_.resize(rhs.size());
std::copy(rhs.begin(), rhs.end(), values_.begin());
}
// specialization: double --> float
template<>
template<>
void CompressedVector<float>::copyValues(const std::vector<double>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: double --> float"<<std::endl;
if(!rhs.size())
{
values_.clear();
return;
}
values_.resize(rhs.size());
std::copy(rhs.begin(), rhs.end(), values_.begin());
}
// specialization: float --> unsigned char
template<>
template<>
void CompressedVector<unsigned char>::copyValues(const std::vector<float>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: float --> unsigned char"<<std::endl;
values_.clear();
// normalized_ = true; // ALWAYS NORMALIZED FOR NON-FLOAT TYPES
if(!rhs.size())
return;
values_.reserve(rhs.size());
for(auto rhs_v : rhs)
{
// if(!rhs.normalized_)
rhs_v = float(rhs_v - i_min) / (i_max - i_min);
unsigned char v_out = rhs_v * std::numeric_limits<unsigned char>::max();
values_.push_back(v_out);
}
}
// specialization: float --> uint16_t
template<>
template<>
void CompressedVector<uint16_t>::copyValues(const std::vector<float>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: float --> uint16_t"<<std::endl;
values_.clear();
// normalized_ = true; // ALWAYS NORMALIZED FOR NON-FLOAT TYPES
if(!rhs.size())
return;
values_.reserve(rhs.size());
for(auto rhs_v : rhs)
{
// if(!rhs.normalized_)
rhs_v = float(rhs_v - i_min) / (i_max - i_min);
uint16_t v_out = rhs_v * std::numeric_limits<uint16_t>::max();
values_.push_back(v_out);
}
}
// specialization: double --> unsigned char
template<>
template<>
void CompressedVector<unsigned char>::copyValues(const std::vector<double>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: double --> unsigned char"<<std::endl;
values_.clear();
// normalized_ = true; // ALWAYS NORMALIZED FOR NON-FLOAT TYPES
if(!rhs.size())
return;
values_.reserve(rhs.size());
for(auto rhs_v : rhs)
{
// if(!rhs.normalized_)
rhs_v = double(rhs_v - i_min) / (i_max - i_min);
unsigned char v_out = rhs_v * std::numeric_limits<unsigned char>::max();
values_.push_back(v_out);
}
}
// specialization: double --> uint16_t
template<>
template<>
void CompressedVector<uint16_t>::copyValues(const std::vector<double>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: double --> uint16_t"<<std::endl;
values_.clear();
// normalized_ = true; // ALWAYS NORMALIZED FOR NON-FLOAT TYPES
if(!rhs.size())
return;
values_.reserve(rhs.size());
for(auto rhs_v : rhs)
{
// if(!rhs.normalized_)
rhs_v = double(rhs_v - i_min) / (i_max - i_min);
uint16_t v_out = rhs_v * std::numeric_limits<uint16_t>::max();
values_.push_back(v_out);
}
}
// specialization: unsigned char --> float
template<>
template<>
void CompressedVector<float>::copyValues(const std::vector<unsigned char>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: unsigned char --> float"<<std::endl;
values_.clear();
// normalized_ = true; // ALWAYS NORMALIZED FOR NON-FLOAT TYPES
if(!rhs.size())
return;
values_.reserve(rhs.size());
for(auto rhs_v : rhs)
{
float rhs_v_0_1 = float(rhs_v) / std::numeric_limits<unsigned char>::max();
values_.push_back(rhs_v_0_1);
}
}
// specialization: uint16_t --> float
template<>
template<>
void CompressedVector<float>::copyValues(const std::vector<uint16_t>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: uint16_t --> float"<<std::endl;
values_.clear();
// normalized_ = true; // ALWAYS NORMALIZED FOR NON-FLOAT TYPES
if(!rhs.size())
return;
values_.reserve(rhs.size());
for(auto rhs_v : rhs)
{
float rhs_v_0_1 = float(rhs_v) / std::numeric_limits<uint16_t>::max();
values_.push_back(rhs_v_0_1);
}
}
// specialization: unsigned char --> double
template<>
template<>
void CompressedVector<double>::copyValues(const std::vector<unsigned char>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: unsigned char --> double"<<std::endl;
values_.clear();
// normalized_ = true; // ALWAYS NORMALIZED FOR NON-FLOAT TYPES
if(!rhs.size())
return;
values_.reserve(rhs.size());
for(auto rhs_v : rhs)
{
double rhs_v_0_1 = double(rhs_v) / std::numeric_limits<unsigned char>::max();
values_.push_back(rhs_v_0_1);
}
}
// specialization: uint16_t --> double
template<>
template<>
void CompressedVector<double>::copyValues(const std::vector<uint16_t>& rhs, double i_min, double i_max)
{
// std::cout<<"specialization: uint16_t --> double"<<std::endl;
values_.clear();
// normalized_ = true; // ALWAYS NORMALIZED FOR NON-FLOAT TYPES
if(!rhs.size())
return;
values_.reserve(rhs.size());
for(auto rhs_v : rhs)
{
double rhs_v_0_1 = double(rhs_v) / std::numeric_limits<uint16_t>::max();
values_.push_back(rhs_v_0_1);
}
}
} // namespace habdec

Wyświetl plik

@ -0,0 +1,117 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <iomanip>
#include <fstream>
#include <vector>
#include <mutex>
#include "IQSource/IQSource.h"
#include "Decoder/Decoder.h"
typedef float TReal; // we operate on float IQ samples
typedef habdec::Decoder<TReal> TDecoder;
// 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_;
}
// decoder and IQ source
TDecoder decoder_;
std::unique_ptr<habdec::IQSource> p_iq_source_;
enum class TransportDataType {kUnknown=0, kChar, kShort, kFloat}; // 8, 16, 32 bits
TransportDataType transport_data_type_ = TransportDataType::kChar;
std::vector<TDecoder::TValue> demod_accumulated_; // acuumulated demod samples, used for GUI display
std::mutex demod_accumulated_mtx_;
// decoded sentences que
std::vector<std::string> senteces_to_log_;
std::mutex senteces_to_log_mtx_;
std::vector<std::string> senteces_to_web_;
std::mutex senteces_to_web_mtx_;
// outgoing commands. used to sync webgui
std::vector<std::string> out_commands_;
std::mutex out_commands_mtx_;
// OPTS:
int device_ = -1; // index to SoapySDR::Device::enumerate()
std::string command_host_ = "0.0.0.0";
int command_port_ = 5555;
std::string station_callsign_ = ""; // habitat upload
double sampling_rate_ = 0;
double frequency_ = 434349500.0f;
double gain_ = 15;
bool biast_ = false;
float baud_ = 300;
int rtty_ascii_bits_ = 8;
float rtty_ascii_stops_ = 2;
bool live_print_ = true;
bool afc_ = false;
static bool DumpToFile(std::string fName)
{
using namespace std;
try{
fstream oFile(fName, fstream::out);
oFile<<"device = "<<GLOBALS::get().device_<<endl;
oFile<<"sampling_rate = "<<GLOBALS::get().sampling_rate_<<endl;
oFile<<"port = "<<GLOBALS::get().command_host_<<":"<<GLOBALS::get().command_port_<<endl;
oFile<<"station = "<<GLOBALS::get().station_callsign_<<endl;
oFile<<"freq = "<<setprecision(9)<<GLOBALS::get().frequency_/1e6<<endl;
oFile<<"gain = "<<GLOBALS::get().gain_<<endl;
oFile<<"biast = "<<GLOBALS::get().biast_<<endl;
oFile<<"print = "<<GLOBALS::get().live_print_<<endl;
oFile<<"rtty = "<<GLOBALS::get().baud_<<endl;
oFile<<"rtty = "<<GLOBALS::get().rtty_ascii_bits_<<endl;
oFile<<"rtty = "<<GLOBALS::get().rtty_ascii_stops_<<endl;
oFile<<"afc = "<<GLOBALS::get().afc_<<endl;
}
catch (exception& e) {
cout<<"Can't save config "<<fName<<endl;
return false;
}
return true;
}
private:
GLOBALS() {};
};

Wyświetl plik

@ -0,0 +1,102 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <iostream>
#include <cstdint>
#include "Decoder/SpectrumInfo.h"
#include "CompressedVector.h"
struct SpectrumInfoHeader
{
int32_t header_size_ = (int32_t)sizeof(SpectrumInfoHeader);
float noise_floor_ = 0;
float noise_variance_ = 0;
float sampling_rate_ = 0;
float shift_ = 0;
int32_t peak_left_ = 0;
int32_t peak_right_ = 0;
int32_t peak_left_valid_ = 0;
int32_t peak_right_valid_ = 0;
float min_ = 0;
float max_ = 0;
// int32_t normalized_ = 0;
int32_t type_size_ = 0;
int32_t size_ = 0;
};
struct DemodHeader
{
int32_t header_size_ = sizeof(DemodHeader);
float min_ = 0;
float max_ = 0;
int32_t type_size_ = 0;
int32_t size_ = 0;
};
template<typename TSpectrumInfo, typename TTransport>
void SerializeSpectrum(const TSpectrumInfo& spectrum_info, std::stringstream& ostr, TTransport* unused)
{
// convert spectrum_info values to type TTransport
habdec::CompressedVector<TTransport> compressed(spectrum_info);
// make header
SpectrumInfoHeader header;
header.noise_floor_ = spectrum_info.noise_floor_;
header.noise_variance_ = spectrum_info.noise_variance_;
header.sampling_rate_ = spectrum_info.sampling_rate_;
header.shift_ = spectrum_info.shift_;
header.peak_left_ = spectrum_info.peak_left_;
header.peak_right_ = spectrum_info.peak_right_;
header.peak_left_valid_ = spectrum_info.peak_left_valid_;
header.peak_right_valid_ = spectrum_info.peak_right_valid_;
header.size_ = spectrum_info.size();
header.min_ = compressed.min_;
header.max_ = compressed.max_;
header.type_size_ = sizeof(TTransport);
ostr.write( reinterpret_cast<char*>(&header), sizeof(header) );
ostr.write( reinterpret_cast<char*>( compressed.values_.data()), compressed.values_.size() * sizeof(TTransport) );
}
template<typename DemodVector, typename TTransport>
void SerializeDemodulation(const DemodVector& vec, std::stringstream& ostr, TTransport* unused)
{
habdec::CompressedVector<TTransport> compressed(vec);
// make header
DemodHeader header;
header.size_ = vec.size();
header.min_ = compressed.min_;
header.max_ = compressed.max_;
header.type_size_ = sizeof(TTransport);
ostr.write( reinterpret_cast<char*>(&header), sizeof(header) );
ostr.write( reinterpret_cast<char*>( compressed.values_.data()), compressed.values_.size() * sizeof(TTransport) );
}

Wyświetl plik

@ -0,0 +1,338 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#include "program_options.h"
#include <signal.h>
#include <string>
#include <vector>
#include <iostream>
#include <SoapySDR/Device.hpp>
#include <SoapySDR/Formats.hpp>
#include "IQSource/IQSource_SoapySDR.h"
#include "Decoder/Decoder.h"
#include "common/console_colors.h"
#include "GLOBALS.h"
#include "server.h"
bool G_DO_EXIT = false;
using namespace std;
void PrintDevicesList(const SoapySDR::KwargsList& device_list)
{
int DEV_NUM = 0;
cout<<endl;
for(const auto& dev : device_list)
{
cout<<C_RED<<DEV_NUM++<<":"<<C_OFF<<endl;
for(const auto& kv : dev)
cout<<'\t'<<kv.first<<" "<<kv.second<<endl;
// print sampling rates
auto p_device = SoapySDR::Device::make(dev);
std::vector<double> sampling_rates = p_device->listSampleRates(SOAPY_SDR_RX, 0);
sort(sampling_rates.begin(), sampling_rates.end());
cout<<"\tSampling Rates:"<<endl;
int sr_index = 0;
for(auto sr : sampling_rates)
cout<<"\t\t"<<C_MAGENTA<<sr<<C_OFF<<endl;
cout<<endl;
}
}
bool SetupDevice()
{
SoapySDR::KwargsList device_list = SoapySDR::Device::enumerate();
if(!device_list.size())
{
cout<<"\nNo Devices found."<<endl;
return false;
}
else
{
cout<<"\nAvailable devices:";
PrintDevicesList(device_list);
cout<<endl;
}
int device_index = GLOBALS::get().device_;
if( device_index >= int(device_list.size()) )
{
cout<<C_RED<<"No device with number "<<device_index<<endl;
return false;
}
if( device_list.size() == 1 )
{
device_index = 0;
}
else if(device_index < 0)
{
cout<<C_MAGENTA<<"No SDR device specified. Select one by specifying it's"<<C_RED<<" NUMBER"<<C_OFF<<endl;
cout<<C_MAGENTA<<"Available Devices:"<<C_OFF<<endl;
int DEV_NUM = 0;
PrintDevicesList(device_list);
cout<<C_OFF<<endl;
return false;
}
if(!GLOBALS::get().sampling_rate_)
{
PrintDevicesList(device_list);
cout<<C_RED<<"Sampling Rate not set."<<C_OFF<<endl;
return false;
}
// setup DEVICE
//
auto& device = device_list[device_index];
cout<<"Running with "<<device["driver"]<<endl<<endl;
GLOBALS::get().p_iq_source_.reset(new habdec::IQSource_SoapySDR);
if(!GLOBALS::get().p_iq_source_)
{
cout<<C_RED<<"Failed creating SoapySDR device. EXIT."<<C_OFF<<endl;
return 1;
}
GLOBALS::get().p_iq_source_->setOption("SoapySDR_Kwargs", &device);
if( !GLOBALS::get().p_iq_source_->init() )
{
cout<<C_RED<<"IQSource_SoapySDR::init failed."<<C_OFF<<endl;
return 1;
}
double freq = GLOBALS::get().frequency_;
GLOBALS::get().p_iq_source_->setOption("frequency_double", &freq);
double gain = GLOBALS::get().gain_;
GLOBALS::get().p_iq_source_->setOption("gain_double", &gain);
double biastee = GLOBALS::get().biast_;
GLOBALS::get().p_iq_source_->setOption("biastee_double", &biastee);
GLOBALS::get().p_iq_source_->setOption("sampling_rate_double", &GLOBALS::get().sampling_rate_);
return true;
}
void DECODER_FEED_THREAD()
{
using namespace std;
cout<<"Start DECODER_FEED_THREAD"<<endl;
auto& p_iq_src = GLOBALS::get().p_iq_source_;
if(!p_iq_src)
return;
if(!p_iq_src->start())
{
cout<<C_RED<<"Failed to start device. Exit DECODER_FEED_THREAD."<<C_OFF<<endl;
return;
}
if(!p_iq_src->isRunning())
{
cout<<C_RED<<"Device not running. Exit DECODER_FEED_THREAD."<<C_OFF<<endl;
return;
}
//////
//
typedef std::chrono::nanoseconds TDur;
auto& DECODER = GLOBALS::get().decoder_;
habdec::IQVector<TReal> samples;
samples.resize(256*256);
samples.samplingRate( p_iq_src->samplingRate() );
while(!G_DO_EXIT)
{
auto _start = std::chrono::high_resolution_clock::now();
size_t count = p_iq_src->get( samples.data(), samples.size() );
DECODER.pushSamples(samples);
DECODER(); // DECODE !
// AFC - don't do this too often. Too unstable, needs more work.
static auto last_afc_time = std::chrono::high_resolution_clock::now();
if( std::chrono::duration_cast< std::chrono::seconds >
(std::chrono::high_resolution_clock::now() - last_afc_time).count() > 5
)
{
double freq_corr = DECODER.getFrequencyCorrection();
if(GLOBALS::get().afc_)
{
if( 100 < abs(freq_corr) )
{
GLOBALS::get().frequency_ += freq_corr;
double f = GLOBALS::get().frequency_;
p_iq_src->setOption("frequency_double", &f);
DECODER.resetFrequencyCorrection(freq_corr);
last_afc_time = std::chrono::high_resolution_clock::now();
// notify webgui
{
lock_guard<mutex> _lock( GLOBALS::get().out_commands_mtx_ );
GLOBALS::get().out_commands_.emplace_back("cmd::set:frequency=" + to_string(f / 1e6));
}
}
}
}
TDur _duration = std::chrono::duration_cast<TDur>(std::chrono::high_resolution_clock::now() - _start);
// accumulate demod samples to display more
{
std::lock_guard<std::mutex> _lock(GLOBALS::get().demod_accumulated_mtx_);
const size_t max_sz = DECODER.getDecimatedSamplingRate() /
DECODER.getSymbolRate() * 50; // 50 symbols
auto demod = DECODER.getDemodulated();
auto& demod_acc = GLOBALS::get().demod_accumulated_;
demod_acc.insert( demod_acc.end(), demod.cbegin(), demod.cend() );
// remove leading values
if( demod_acc.size() > max_sz)
demod_acc.erase( demod_acc.begin(), demod_acc.begin() + demod_acc.size() - max_sz );
}
}
}
void HAB_UPLOAD_THREAD()
{
using namespace std;
while(!G_DO_EXIT)
{
this_thread::sleep_for( chrono::duration<double, milli>(500) );
vector<string> sentences;
{
lock_guard<mutex> _lock( GLOBALS::get().senteces_to_log_mtx_ );
sentences = move( GLOBALS::get().senteces_to_log_ );
}
if(GLOBALS::get().station_callsign_ != "")
{
for(auto& sentence : sentences)
{
string cmd = "python ./habLogger.py ";
cmd += sentence;
cmd += " ";
cmd += GLOBALS::get().station_callsign_;
auto res = system(cmd.c_str());
cout<<"HAB upload res: "<<res<<endl;
}
}
}
}
int main(int argc, char** argv)
{
signal( SIGINT, [](int){exit(1);} );
signal( SIGILL, [](int){exit(1);} );
signal( SIGFPE, [](int){exit(1);} );
signal( SIGSEGV, [](int){exit(1);} );
signal( SIGTERM, [](int){exit(1);} );
signal( SIGABRT, [](int){exit(1);} );
// thousands separator
struct thousand_separators : std::numpunct<char>
{
char do_thousands_sep() const { return ','; }
string do_grouping() const { return "\3"; }
};
try{
std::cout.imbue( std::locale(locale(""), new thousand_separators) );
}
catch(exception& e) {
}
// setup GLOBALS
prog_opts(argc, argv);
// setup SoapySDR device
if(!SetupDevice())
{
cout<<C_RED<<"Failed Device Setup. EXIT."<<C_OFF<<endl;
return 1;
}
if(GLOBALS::get().station_callsign_ == "")
cout<<C_RED<<"No --station parameter set. HAB Upload disabled."<<C_OFF<<endl;
// initial options
auto& DECODER = GLOBALS::get().decoder_;
DECODER.baud(GLOBALS::get().baud_);
DECODER.rtty_bits(GLOBALS::get().rtty_ascii_bits_);
DECODER.rtty_stops(GLOBALS::get().rtty_ascii_stops_);
DECODER.lowpass_bw(.05);
DECODER.lowpass_trans(.0025);
DECODER.livePrint( GLOBALS::get().live_print_ );
// for every decoded message
// put it on two ques: websocket upload, HAB upload
DECODER.success_callback_ =
[](std::string callsign, std::string data, std::string crc)
{
{
lock_guard<mutex> _lock( GLOBALS::get().senteces_to_log_mtx_ );
GLOBALS::get().senteces_to_log_.emplace_back( callsign + "," + data + "*" + crc );
}
{
lock_guard<mutex> _lock( GLOBALS::get().senteces_to_web_mtx_ );
GLOBALS::get().senteces_to_web_.emplace_back( callsign + "," + data + "*" + crc );
}
GLOBALS::DumpToFile("./habdecWebsocketServer.opts");
};
// feed decoder with IQ samples
std::thread* decoder_feed_thread = new std::thread(DECODER_FEED_THREAD);
// HAB upload
std::thread* hab_upload_thread = new std::thread(HAB_UPLOAD_THREAD);
// websocket server thread. this call is blocking
RunCommandServer( GLOBALS::get().command_host_ , GLOBALS::get().command_port_ );
G_DO_EXIT = true;
decoder_feed_thread->join();
hab_upload_thread->join();
return 0;
}

Wyświetl plik

@ -0,0 +1,193 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#include <string>
#include <iostream>
#include <fstream>
#include <regex>
#include <boost/program_options.hpp>
#include "GLOBALS.h"
#include "common/console_colors.h"
void prog_opts(int ac, char* av[])
{
namespace po = boost::program_options;
using namespace std;
try
{
po::options_description generic("CLI opts");
generic.add_options()
("help", "Display help message")
("device", po::value<int>()->default_value(-1), "SDR Device Numer")
("sampling_rate", po::value<double>()->default_value(0), "Sampling Rate, as supported by device")
("port", po::value<string>()->default_value("5555"), "Command Port, example: --port 127.0.0.1:5555")
("station", po::value<string>()->default_value(""), "HABHUB station callsign")
("freq", po::value<float>(), "frequency in MHz")
("gain", po::value<int>(), "gain")
("print", po::value<bool>(), "live print received chars, values: 0, 1")
("rtty", po::value< std::vector<float> >()->multitoken(), "rtty: baud bits stops, example: -rtty 300 8 2")
("biast", po::value<bool>(), "biasT, values: 0, 1")
("bias_t", po::value<bool>(), "biasT, values: 0, 1")
("afc", po::value<bool>(), "Auto Frequency Correction, values: 0, 1")
;
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), "Last run config file. Autosaved on every successfull decode.");
// ("config", po::value<string>(&config_file)->default_value("./habdecWebsocketServer.opts"), "Last run config file. Autosaved on every successfull decode.");
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("device"))
{
GLOBALS::get().device_ = vm["device"].as<int>();
}
if (vm.count("sampling_rate"))
{
GLOBALS::get().sampling_rate_ = vm["sampling_rate"].as<double>();
}
if (vm.count("port")) // [host:][port]
{
smatch match;
regex_match( vm["port"].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 5555
{
GLOBALS::get().command_port_ = stoi(match[1]);
}
else
{
if(match[1] != "") GLOBALS::get().command_host_ = match[1];
if(match[3] != "") GLOBALS::get().command_port_ = stoi(match[3]);
}
}
}
if (vm.count("station"))
{
GLOBALS::get().station_callsign_ = vm["station"].as<string>();
}
if (vm.count("freq"))
{
GLOBALS::get().frequency_ = vm["freq"].as<float>() * 1e6;
}
if (vm.count("gain"))
{
GLOBALS::get().gain_ = vm["gain"].as<int>();
}
if (vm.count("print"))
{
GLOBALS::get().live_print_ = vm["print"].as<bool>();
}
if (vm.count("biast"))
{
GLOBALS::get().biast_ = vm["biast"].as<bool>();
}
if (vm.count("bias_t"))
{
GLOBALS::get().biast_ = vm["bias_t"].as<bool>();
}
if (vm.count("afc"))
{
GLOBALS::get().afc_ = vm["afc"].as<bool>();
}
if (vm.count("rtty"))
{
vector<float> rtty_tokens = vm["rtty"].as< vector<float> >();
if( rtty_tokens.size() != 3 )
{
cout<<C_RED<<"--rtty option needs 3 args: baud ascii-bits stop-bits"<<C_OFF<<endl;
exit(1);
}
if(rtty_tokens[2] != 1 && rtty_tokens[2] != 2)
{
cout<<C_RED<<"Only 1 or 2 stop bits are supported."<<C_OFF<<endl;
exit(1);
}
if(rtty_tokens[1] != 7 && rtty_tokens[1] != 8)
{
cout<<C_RED<<"ASCII Bits must be 7 or 8"<<C_OFF<<endl;
exit(1);
}
GLOBALS::get().baud_ = rtty_tokens[0];
GLOBALS::get().rtty_ascii_bits_ = rtty_tokens[1];
GLOBALS::get().rtty_ascii_stops_ = rtty_tokens[2];
}
}
catch(exception& e)
{
cout << e.what() << "\n";
}
// print globals:
cout<<"Current options: "<<endl;
cout<<"\tdevice: "<<GLOBALS::get().device_<<endl;
cout<<"\tsampling_rate: "<<GLOBALS::get().sampling_rate_<<endl;
cout<<"\tcommand_host: "<<GLOBALS::get().command_host_<<endl;
cout<<"\tcommand_port: "<<GLOBALS::get().command_port_<<endl;
cout<<"\tstation: "<<GLOBALS::get().station_callsign_<<endl;
cout<<"\tfreq: "<<GLOBALS::get().frequency_<<endl;
cout<<"\tgain: "<<GLOBALS::get().gain_<<endl;
cout<<"\tlive_print: "<<GLOBALS::get().live_print_<<endl;
cout<<"\tbaud: "<<GLOBALS::get().baud_<<endl;
cout<<"\trtty_ascii_bits: "<<GLOBALS::get().rtty_ascii_bits_<<endl;
cout<<"\trtty_ascii_stops: "<<GLOBALS::get().rtty_ascii_stops_<<endl;
cout<<"\tbiast: "<<GLOBALS::get().biast_<<endl;
GLOBALS::DumpToFile("./habdecWebsocketServer.opts");
}

Wyświetl plik

@ -0,0 +1,22 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
void prog_opts(int ac, char* av[]);

Wyświetl plik

@ -0,0 +1,471 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#include <cstdlib>
#include <memory>
#include <string>
#include <iostream>
#include <thread>
#include <functional>
#include <regex>
#include <boost/beast/core.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/asio/ip/tcp.hpp>
using boost::asio::ip::tcp;
namespace beast = boost::beast;
namespace websocket = boost::beast::websocket;
#include "common/console_colors.h"
#include "CompressedVector.h"
#include "GLOBALS.h"
#include "NetTransport.h"
extern bool G_DO_EXIT;
bool HandleCommand(const std::string i_command, websocket::stream<tcp::socket>& ws)
{
if(!GLOBALS::get().p_iq_source_)
return false;
using namespace std;
smatch match;
// GET
if(i_command == "get:frequency")
{
double frequency = 0;
GLOBALS::get().p_iq_source_->getOption("frequency_double", &frequency);
frequency /= 1e6;
string o_command = "cmd::set:frequency=" + to_string(frequency);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:gain")
{
double gain = 0;
GLOBALS::get().p_iq_source_->getOption("gain_double", &gain);
string o_command = "cmd::set:gain=" + to_string(gain);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:baud")
{
size_t baud = GLOBALS::get().decoder_.baud();
string o_command = "cmd::set:baud=" + to_string(baud);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:rtty_bits")
{
size_t rtty_bits = GLOBALS::get().decoder_.rtty_bits();
string o_command = "cmd::set:rtty_bits=" + to_string(rtty_bits);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:rtty_stops")
{
float rtty_stops = GLOBALS::get().decoder_.rtty_stops();
string o_command = "cmd::set:rtty_stops=" + to_string(rtty_stops);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:lowpass_bw")
{
string o_command = "cmd::set:lowpass_bw=" + to_string(GLOBALS::get().decoder_.lowpass_bw());
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:lowpass_trans")
{
string o_command = "cmd::set:lowpass_trans=" + to_string(GLOBALS::get().decoder_.lowpass_trans());
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:biastee")
{
double biastee = 0;
GLOBALS::get().p_iq_source_->getOption("biastee_double", &biastee);
string o_command = "cmd::set:biastee=" + to_string(biastee);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:afc")
{
string o_command = "cmd::set:afc=" + to_string(GLOBALS::get().afc_);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:decimation")
{
int decim_factor_log = std::log2( GLOBALS::get().decoder_.getDecimationFactor() );
string o_command = "cmd::set:decimation=" + to_string(decim_factor_log);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if(i_command == "get:sampling_rate")
{
double sr = 0;
GLOBALS::get().p_iq_source_->getOption("sampling_rate_double", &sr);
string o_command = "cmd::info:sampling_rate=" + to_string(sr);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
// SET
else if( regex_match(i_command, match, regex(R"_(set\:frequency=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 )
{
double frequency = stod(match[1]);
frequency *= 1e6;
GLOBALS::get().p_iq_source_->setOption("frequency_double", &frequency);
GLOBALS::get().frequency_ = frequency;
string o_command = "cmd::set:frequency=" + to_string(frequency/1e6);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:decimation=(\d+))_")) && match.size() > 1 )
{
int decim_factor_log = stoi(match[1]);
GLOBALS::get().decoder_.setupDecimationStagesFactor( pow(2,decim_factor_log) );
string o_command = "cmd::set:decimation=" + to_string(decim_factor_log);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:gain=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 )
{
double gain = stod(match[1]);
GLOBALS::get().p_iq_source_->setOption("gain_double", &gain);
string o_command = "cmd::set:gain=" + to_string(gain);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
GLOBALS::get().gain_ = gain;
}
else if( regex_match(i_command, match, regex(R"_(set\:lowpass_bw=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 )
{
cout<<"set lowpass_bw "<<stof(match[1])<<endl;
GLOBALS::get().decoder_.lowpass_bw(stof(match[1]));
string o_command = "cmd::set:lowpass_bw=" + to_string(GLOBALS::get().decoder_.lowpass_bw());
cout<<"speak back "<<o_command<<endl;
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:lowpass_trans=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 )
{
GLOBALS::get().decoder_.lowpass_trans(stof(match[1]));
string o_command = "cmd::set:lowpass_trans=" + to_string(GLOBALS::get().decoder_.lowpass_trans());
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:baud=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 )
{
GLOBALS::get().decoder_.baud( stof(match[1]) );
string o_command = "cmd::set:baud=" + to_string(GLOBALS::get().decoder_.baud());
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:rtty_bits=(\d+))_")) && match.size() > 1 )
{
GLOBALS::get().decoder_.rtty_bits(stoi(match[1]));
string o_command = "cmd::set:rtty_bits=" + to_string(GLOBALS::get().decoder_.rtty_bits());
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:rtty_stops=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 1 )
{
GLOBALS::get().decoder_.rtty_stops(stof(match[1]));
string o_command = "cmd::set:rtty_stops=" + to_string(GLOBALS::get().decoder_.rtty_stops());
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:datasize=(\d+))_")) && match.size() > 1 )
{
int datasize = stoi(match[1]);
if(datasize != 1 && datasize != 2 && datasize != 4)
datasize = 1;
if(datasize == 1) GLOBALS::get().transport_data_type_ = GLOBALS::TransportDataType::kChar; // 8bit
if(datasize == 2) GLOBALS::get().transport_data_type_ = GLOBALS::TransportDataType::kShort;// 16 bit
if(datasize == 4) GLOBALS::get().transport_data_type_ = GLOBALS::TransportDataType::kFloat;// 32bit
string o_command = "cmd::set:datasize=" + to_string(datasize);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:biastee=([0-9])+)_")) && match.size() > 1 )
{
double value = stod(match[1]);
GLOBALS::get().p_iq_source_->setOption("biastee_double", &value);
GLOBALS::get().biast_ = value;
string o_command = "cmd::set:biastee=" + to_string(value);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else if( regex_match(i_command, match, regex(R"_(set\:afc=([0-9])+)_")) && match.size() > 1 )
{
int value = stoi(match[1]);
GLOBALS::get().afc_ = value;
string o_command = "cmd::set:afc=" + to_string(value);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
else
{
cout<<C_RED<<"Unknown command: "<<i_command<<C_OFF<<endl;
}
return true;
}
template<typename T>
void ShrinkVector(T& vec, size_t new_size)
{
if(new_size >= vec.size())
return;
for(size_t i=0; i<new_size; ++i)
{
float i_0_1 = float(i) / new_size;
size_t I = i_0_1 * vec.size();
vec[i] = vec[I];
}
vec.resize(new_size);
}
// serializes spectrum info
size_t SpectrumToStream(std::stringstream& res_stream, float zoom, int resolution)
{
using namespace std;
auto spectrum_info = GLOBALS::get().decoder_.getSpectrumInfo();
if(!spectrum_info.size())
return 0;
// zoom - select bins from center
zoom = min(max(zoom, 0.01f), 0.99f);
const size_t zoom_slice_begin = zoom/2 * spectrum_info.size();
const size_t zoom_slice_end = (1.0f-zoom/2) * spectrum_info.size();
spectrum_info.erase( spectrum_info.begin() + zoom_slice_end, spectrum_info.end() );
spectrum_info.erase( spectrum_info.begin(), spectrum_info.begin() + zoom_slice_begin);
spectrum_info.peak_left_ -= zoom_slice_begin;
if(spectrum_info.peak_left_ < 0 || spectrum_info.peak_left_ > spectrum_info.size())
{
spectrum_info.peak_left_ = 0;
spectrum_info.peak_left_valid_ = false;
}
spectrum_info.peak_right_ -= zoom_slice_begin;
if(spectrum_info.peak_right_ < 0 || spectrum_info.peak_right_ > spectrum_info.size())
{
spectrum_info.peak_right_ = 0;
spectrum_info.peak_right_valid_ = false;
}
// transfer resolution - leave only 'resolution' number of bins
//
if(resolution < spectrum_info.size())
{
spectrum_info.peak_left_ = double(spectrum_info.peak_left_) * resolution / spectrum_info.size();
spectrum_info.peak_right_ = double(spectrum_info.peak_right_) * resolution / spectrum_info.size();
ShrinkVector(spectrum_info, resolution);
}
// choose transport bit resolution: 8, 16, 32 bit
//
if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kChar )
SerializeSpectrum( spectrum_info, res_stream, (unsigned char*)0 );
if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kShort )
SerializeSpectrum( spectrum_info, res_stream, (unsigned short int*)0 );
if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kFloat )
SerializeSpectrum( spectrum_info, res_stream, (float*)0 );
return spectrum_info.size();
}
// serialize demod
size_t DemodToStream(std::stringstream& res_stream, int resolution)
{
std::vector<TDecoder::TValue> demod_acc;
{
std::lock_guard<std::mutex> _lock(GLOBALS::get().demod_accumulated_mtx_);
demod_acc = GLOBALS::get().demod_accumulated_;
}
if(demod_acc.size())
{
ShrinkVector(demod_acc, resolution);
// choose transport datatype: 8, 16, 32 bit
if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kChar )
SerializeDemodulation( demod_acc, res_stream, (unsigned char*)0 );
if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kShort )
SerializeDemodulation( demod_acc, res_stream, (unsigned short int*)0 );
if( GLOBALS::get().transport_data_type_ == GLOBALS::TransportDataType::kFloat )
SerializeDemodulation( demod_acc, res_stream, (float*)0 );
}
return demod_acc.size();
}
void DoSession(tcp::socket& i_socket)
{
using namespace std;
// allow just one session
static std::atomic<bool> close_session{false};
static std::atomic<bool> session_running{false};
// close previous session
while(session_running)
{
close_session = true;
std::this_thread::sleep_for( ( std::chrono::duration<double, std::milli>(300) ));
}
try {
websocket::stream<tcp::socket> ws{std::move(i_socket)};
ws.accept();
session_running = true;
// this line does not work
// ws.accept_ex([](websocket::response_type &m) { m.insert(beast::http::field::server, "habdec_server"); });
ws.auto_fragment(false);
while(!G_DO_EXIT)
{
if(close_session)
{
cout<<"Closing Session."<<endl;
close_session = false;
session_running = false;
return;
}
beast::multi_buffer buffer;
ws.read(buffer);
string command = beast::buffers_to_string(buffer.data());
buffer.consume(buffer.size());
smatch match;
// power,res=resolution_value,zoom=zoom_value
if( regex_match(command, match, regex(R"_(cmd\:\:power\:res=(\d+),zoom=([+-]?([0-9]*[.])?[0-9]+))_")) && match.size() > 2 )
{
stringstream res_stream;
res_stream<<"PWR_";
if(SpectrumToStream( res_stream, stof(match[2]), stoi(match[1]) ))
{
ws.binary(true);
ws.write( boost::asio::buffer(res_stream.str()) );
}
}
// demod=resolution
else if( regex_match(command, match, regex(R"_(cmd\:\:demod\:res=(\d+))_")) && match.size() > 1 )
{
stringstream res_stream;
res_stream<<"DEM_";
if( DemodToStream( res_stream, stoi(match[1]) ) )
{
ws.binary(true);
ws.write( boost::asio::buffer(res_stream.str()) );
}
}
// cmd::liveprint
else if( regex_match(command, match, regex(R"_(cmd\:\:liveprint)_")) && match.size() > 0 )
{
string o_command = "cmd::info:liveprint=" + GLOBALS::get().decoder_.getRTTY();
ws.text(true);
ws.write( boost::asio::buffer(o_command.c_str(), o_command.size()) );
}
// cmd::****
else if(command.size()>5 && command.substr(0,5) == "cmd::")
{
cout<<C_MAGENTA<<"Command "<<command<<C_OFF<<endl;
ws.text(true);
HandleCommand(command.substr(5), ws);
}
// check for new sentences
vector<string> sentences;
{
lock_guard<mutex> _lock( GLOBALS::get().senteces_to_web_mtx_ );
sentences = std::move(GLOBALS::get().senteces_to_web_);
}
for(auto& sentence : sentences)
{
string o_command = "cmd::info:sentence=" + sentence;
ws.text(true);
ws.write( boost::asio::buffer( o_command.c_str(), o_command.size()) );
}
// check for out commands
vector<string> out_cmds;
{
lock_guard<mutex> _lock( GLOBALS::get().out_commands_mtx_ );
out_cmds = std::move(GLOBALS::get().out_commands_);
}
for(auto& cmd : out_cmds)
{
ws.text(true);
ws.write( boost::asio::buffer( cmd.c_str(), cmd.size()) );
}
}
}
catch(const boost::system::system_error& se) {
if(se.code() != websocket::error::closed)
cout << "Error: boost::system::system_error: " << se.code().message() << endl;
else
cout << "Session Closed. " << se.code().message() << endl;
}
catch(const exception& e) {
cout << "Session Error: " << e.what() << endl;
}
session_running = false;
cout << "Session END."<<endl;
}
void RunCommandServer(const std::string command_host, const int command_port)
{
using namespace std;
using tcp = boost::asio::ip::tcp;
if(!command_port || command_host == "")
{
cout<<C_RED<<"No Command host or port."<<C_OFF<<endl;
return;
}
while(!G_DO_EXIT)
{
if (!GLOBALS::get().p_iq_source_)
continue;
try {
auto const address = boost::asio::ip::make_address( command_host );
auto const port = static_cast<unsigned short>( command_port );
boost::asio::io_context ioc{1};
tcp::acceptor acceptor{ioc, {address, port}};
while(!G_DO_EXIT)
{
tcp::socket socket{ioc};
acceptor.accept(socket); // Block until we get a connection
cout<<C_MAGENTA<<"\nNew Client"<<C_OFF<<endl;
std::thread{std::bind(&DoSession, std::move(socket))}.detach();
}
}
catch(const exception& e) {
cout<<C_RED<<"Failed starting Command Server\n"<<e.what()<<C_OFF<<endl;
std::this_thread::sleep_for( ( std::chrono::duration<double, std::milli>(1000) ));
}
}
}

Wyświetl plik

@ -0,0 +1,26 @@
/*
Copyright 2018 Michal Fratczak
This file is part of habdec.
habdec 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.
habdec 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 habdec. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <string>
#include <thread>
void RunCommandServer(const std::string command_host, const int command_port);

Plik binarny nie jest wyświetlany.

Po

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