././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1778283194.3989341
not1mm-26.5.8/ 0000755 0001750 0001750 00000000000 15177471272 012710 5 ustar 00mbridak mbridak ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1731352272.0
not1mm-26.5.8/LICENSE 0000644 0001750 0001750 00000104515 14714453320 013711 0 ustar 00mbridak mbridak GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
Copyright (C)
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1778283194.3977153
not1mm-26.5.8/PKG-INFO 0000644 0001750 0001750 00000015570 15177471272 014015 0 ustar 00mbridak mbridak Metadata-Version: 2.4
Name: not1mm
Version: 26.5.8
Summary: NOT1MM Logger
Author-email: Michael Bridak
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/mbridak/not1mm
Project-URL: Bug Tracker, https://github.com/mbridak/not1mm/issues
Classifier: Programming Language :: Python :: 3
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: X11 Applications :: Qt
Classifier: Operating System :: POSIX :: Linux
Classifier: Intended Audience :: End Users/Desktop
Classifier: Natural Language :: English
Classifier: Topic :: Communications :: Ham Radio
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: PyQt6
Requires-Dist: requests
Requires-Dist: dicttoxml
Requires-Dist: xmltodict
Requires-Dist: pyserial
Requires-Dist: sounddevice
Requires-Dist: soundfile
Requires-Dist: numpy
Requires-Dist: notctyparser>=23.6.21
Requires-Dist: rapidfuzz
Requires-Dist: appdata
Requires-Dist: adif_io
Dynamic: license-file
# Not1MM

The worlds #1 unfinished contest logger *According to my daughter Corinna.
[](https://pypi.org/project/not1mm/)
[](https://www.gnu.org/licenses/gpl-3.0)
[](https://www.python.org/downloads/)
[](https://pypi.org/project/PyQt6/)
[](https://xkcd.com/1695/)
[](https://pepy.tech/projects/not1mm)
[](https://pepy.tech/projects/not1mm)

### The Elephant in the Room
Not1MM's interface is a blatant ripoff of N1MM. It is NOT N1MM and any problem
you have with this software should in no way reflect on their software.
### Not1MM is NOT ment for interoperability with N1MM+
I wake up, take my first sip of coffee and am greeted by a lovely heartfelt [message](TomsAMassiveTwat.md) from Tom Wagner.
So I feel something may need to be clarified. Not1MM is... NOT N1MM neither is it N1MM+ or even N1MMPlus.
They're not ment to work with each other. It does send N1MM packets, but that's for nodered scoreboards, not Tom's beloved program.
You shouldn't bother Tom or his Team. They be cranky...
### The What
Not1MM is, in my opinion, a usable amateur radio, or HAM, contest logger. It's
written in Python 3.10+, and uses Qt6 framework for the graphical interface
and SQLite for the database.
### Target Environment
The primary target for this application is Linux. It may be able to run on other
platforms, BSD and Windows. But I don't have a way, or desire, to directly support them.
I've recently purchased an M4 Mac Mini, So I'll probably put more effort into that platform as well.
### The Why
**Currently this exists for my own personal amusement**. I've recently retired
after 35+ years working for 'The Phone Company', GTE -> Verizon -> Frontier.
And being a Gentleman of Leisure, needed something to do in my free time.
I'm a casual contester and could not find any contesting software for Linux that
I wanted to use. There is [Tucnak](http://tucnak.nagano.cz/) which is very robust
and mature. It just wasn't for me.
## Code Maturity & Current Multi Multi Development Focus
Not1MM is, at times, fairly stable. Recently, it would seem that I'm desperately trying to change that. The current focus of development is adding support for [Multi Multi](Multi-Multi.md) contest operations. It is something that I have no practical experience in. So you can expect the same quality of code fit and finish.
## Our Code Contributors ✨
I wish to thank those who've contributed to the project. Below is an automatically
generated, 'cause I'm lazy, list of those who've submitted PR's.
## Recent Changes
- [2026-05-07] Merge remote-tracking branch 'origin/master' into 525-rework-pacc
- Add Dutch contest logic to points calculation in PACC
- Add call history support to PACC
- Merge pull request #561 from microphonon/dual_mode_VFO_bump
- Merge pull request #560 from mbridak/530-wrong-checkpartial-hilighting-in-telnet-column
- [2026-05-06] Merge pull request #556 from df7cb Add context menu on bandmap spots
- trimmed configuration.ui file with trim_ui.sh script to stop uic parser from crashing
- Merge pull request #559 from microphonon Keyboard control to bump VFO frequency
- [2026-05-05] Fix crash in cabrillo generation
- [2026-05-04] Merge pull request #549 from df7cb Remember CQ frequencies in bandmap
- Merge pull request #548 from df7cb Send serials with CW cut numbers
- Merge pull request #547 from df7cb Remove padding around bandmap scroll area, Convert bandmap to kHz
- Merge pull request #551 from mbridak Refactor CW mode handling in Cabrillo format for multiple plugins
- [2026-05-01] Merge pull request #544 from mbridak Change LCD number color from white to green in VfoWindow
See [CHANGELOG.md](CHANGELOG.md) for prior changes.
## Installation
### TL;DR
#### Prerequisites
Not1MM requires:
- PyQt6
- libportaudio2
- libxcb-cursor0 (maybe... Depends on the distro)
#### One liner install
```bash
curl -LsSf uvx.sh/not1mm/install.sh | sh
```
For more in depth info, please see the [installation](INSTALL.md) section.
## Documentation
I've nuked 90% of the README.md and moved it to a LaTeX file. So now you can get the [user manual](https://github.com/mbridak/not1mm/raw/master/not1mm.pdf) as a PDF file. I know some WILL NOT LIKE THIS. Sorry, not sorry.
## Features
A quick feature list, See the user manual for more details.
- 45+ [supported contests](Working_Contests.md)
- Lookup, QRZ and HamQTH
- CAT Control, rigctld and flrig
- CW Keyer Interface, winkeyer and cwdaemon
- Cluster and Bandmap
- Rotator control, rotctld
- [Multi Multi](Multi-Multi.md) (The super sketchy not ready for prime time)
- N1MM Packet output for nodered
- WSJT-X FT8/FT4/ETC and FLDIGI RTTY
- ADIF and Cabrillo output.
- And *Other Stuff*
## Known Issues
- Hamlib before 4.6.3 had a problem with sending CW and changing/reading the keying speed.
- wfview before version 2.2 has issues with frequency reporting and CW sending.
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1778283106.0
not1mm-26.5.8/README.md 0000644 0001750 0001750 00000013547 15177471142 014175 0 ustar 00mbridak mbridak
# Not1MM

The worlds #1 unfinished contest logger *According to my daughter Corinna.
[](https://pypi.org/project/not1mm/)
[](https://www.gnu.org/licenses/gpl-3.0)
[](https://www.python.org/downloads/)
[](https://pypi.org/project/PyQt6/)
[](https://xkcd.com/1695/)
[](https://pepy.tech/projects/not1mm)
[](https://pepy.tech/projects/not1mm)

### The Elephant in the Room
Not1MM's interface is a blatant ripoff of N1MM. It is NOT N1MM and any problem
you have with this software should in no way reflect on their software.
### Not1MM is NOT ment for interoperability with N1MM+
I wake up, take my first sip of coffee and am greeted by a lovely heartfelt [message](TomsAMassiveTwat.md) from Tom Wagner.
So I feel something may need to be clarified. Not1MM is... NOT N1MM neither is it N1MM+ or even N1MMPlus.
They're not ment to work with each other. It does send N1MM packets, but that's for nodered scoreboards, not Tom's beloved program.
You shouldn't bother Tom or his Team. They be cranky...
### The What
Not1MM is, in my opinion, a usable amateur radio, or HAM, contest logger. It's
written in Python 3.10+, and uses Qt6 framework for the graphical interface
and SQLite for the database.
### Target Environment
The primary target for this application is Linux. It may be able to run on other
platforms, BSD and Windows. But I don't have a way, or desire, to directly support them.
I've recently purchased an M4 Mac Mini, So I'll probably put more effort into that platform as well.
### The Why
**Currently this exists for my own personal amusement**. I've recently retired
after 35+ years working for 'The Phone Company', GTE -> Verizon -> Frontier.
And being a Gentleman of Leisure, needed something to do in my free time.
I'm a casual contester and could not find any contesting software for Linux that
I wanted to use. There is [Tucnak](http://tucnak.nagano.cz/) which is very robust
and mature. It just wasn't for me.
## Code Maturity & Current Multi Multi Development Focus
Not1MM is, at times, fairly stable. Recently, it would seem that I'm desperately trying to change that. The current focus of development is adding support for [Multi Multi](Multi-Multi.md) contest operations. It is something that I have no practical experience in. So you can expect the same quality of code fit and finish.
## Our Code Contributors ✨
I wish to thank those who've contributed to the project. Below is an automatically
generated, 'cause I'm lazy, list of those who've submitted PR's.
## Recent Changes
- [2026-05-07] Merge remote-tracking branch 'origin/master' into 525-rework-pacc
- Add Dutch contest logic to points calculation in PACC
- Add call history support to PACC
- Merge pull request #561 from microphonon/dual_mode_VFO_bump
- Merge pull request #560 from mbridak/530-wrong-checkpartial-hilighting-in-telnet-column
- [2026-05-06] Merge pull request #556 from df7cb Add context menu on bandmap spots
- trimmed configuration.ui file with trim_ui.sh script to stop uic parser from crashing
- Merge pull request #559 from microphonon Keyboard control to bump VFO frequency
- [2026-05-05] Fix crash in cabrillo generation
- [2026-05-04] Merge pull request #549 from df7cb Remember CQ frequencies in bandmap
- Merge pull request #548 from df7cb Send serials with CW cut numbers
- Merge pull request #547 from df7cb Remove padding around bandmap scroll area, Convert bandmap to kHz
- Merge pull request #551 from mbridak Refactor CW mode handling in Cabrillo format for multiple plugins
- [2026-05-01] Merge pull request #544 from mbridak Change LCD number color from white to green in VfoWindow
See [CHANGELOG.md](CHANGELOG.md) for prior changes.
## Installation
### TL;DR
#### Prerequisites
Not1MM requires:
- PyQt6
- libportaudio2
- libxcb-cursor0 (maybe... Depends on the distro)
#### One liner install
```bash
curl -LsSf uvx.sh/not1mm/install.sh | sh
```
For more in depth info, please see the [installation](INSTALL.md) section.
## Documentation
I've nuked 90% of the README.md and moved it to a LaTeX file. So now you can get the [user manual](https://github.com/mbridak/not1mm/raw/master/not1mm.pdf) as a PDF file. I know some WILL NOT LIKE THIS. Sorry, not sorry.
## Features
A quick feature list, See the user manual for more details.
- 45+ [supported contests](Working_Contests.md)
- Lookup, QRZ and HamQTH
- CAT Control, rigctld and flrig
- CW Keyer Interface, winkeyer and cwdaemon
- Cluster and Bandmap
- Rotator control, rotctld
- [Multi Multi](Multi-Multi.md) (The super sketchy not ready for prime time)
- N1MM Packet output for nodered
- WSJT-X FT8/FT4/ETC and FLDIGI RTTY
- ADIF and Cabrillo output.
- And *Other Stuff*
## Known Issues
- Hamlib before 4.6.3 had a problem with sending CW and changing/reading the keying speed.
- wfview before version 2.2 has issues with frequency reporting and CW sending.
././@PaxHeader 0000000 0000000 0000000 00000000034 00000000000 010212 x ustar 00 28 mtime=1778283194.2244055
not1mm-26.5.8/not1mm/ 0000755 0001750 0001750 00000000000 15177471272 014123 5 ustar 00mbridak mbridak ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1731352272.0
not1mm-26.5.8/not1mm/__init__.py 0000644 0001750 0001750 00000000000 14714453320 016210 0 ustar 00mbridak mbridak ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1778214550.0
not1mm-26.5.8/not1mm/__main__.py 0000644 0001750 0001750 00000576370 15177263226 016235 0 ustar 00mbridak mbridak #!/usr/bin/env python3
"""
not1mm Contest logger
Email: michael.bridak@gmail.com
GPL V3
Purpose: Provides main logging window and a crap ton more.
"""
# pylint: disable=unused-import, c-extension-no-member, no-member, invalid-name, too-many-lines, no-name-in-module
# pylint: disable=logging-fstring-interpolation, logging-not-lazy, line-too-long, bare-except
# alt cluster hamqth.com 7300
import datetime
import time
import importlib
import locale
import logging
from logging.handlers import RotatingFileHandler
import os
import queue
import socket
import sys
import uuid
from json import dumps, loads
from json.decoder import JSONDecodeError
from pathlib import Path
from shutil import copyfile
import notctyparser
from PyQt6 import QtCore, QtGui, QtWidgets, uic, QtNetwork
from PyQt6.QtCore import QDir, Qt, QThread, QSettings, QCoreApplication
from PyQt6.QtGui import (
QFontDatabase,
QColorConstants,
QPalette,
QColor,
QPixmap,
QFont,
QCloseEvent,
QKeyEvent,
)
from PyQt6.QtWidgets import (
QFileDialog,
QSplashScreen,
QApplication,
QPushButton,
QLineEdit,
)
from PyQt6.QtCore import QT_VERSION_STR, PYQT_VERSION_STR
from not1mm.lib.about import About
from not1mm.lib.cwinterface import CW
from not1mm.lib.database import DataBase
from not1mm.lib.edit_macro import EditMacro
from not1mm.lib.edit_opon import OpOn
from not1mm.lib.edit_rove import Rove
from not1mm.lib.edit_station import EditStation
from not1mm.lib.multicast import Multicast
from not1mm.lib.ham_utility import (
bearing,
bearing_with_latlon,
calculate_wpx_prefix,
distance,
distance_with_latlon,
get_logged_band,
getband,
reciprocal,
fakefreq,
)
# from not1mm.lib.multicast import Multicast
from not1mm.lib.n1mm import N1MM
from not1mm.lib.new_contest import NewContest
from not1mm.lib.super_check_partial import SCP
from not1mm.lib.select_contest import SelectContest
from not1mm.lib.settings import Settings
from not1mm.lib.version import __version__
from not1mm.lib.versiontest import VersionTest
from not1mm.lib.ft8_watcher import FT8Watcher
from not1mm.lib.fldigi_sendstring import FlDigi_Comm
import not1mm.fsutils as fsutils
from not1mm.logwindow import LogWindow
from not1mm.checkwindow import CheckWindow
from not1mm.dxcc_tracker import DXCCWindow
from not1mm.zone_tracker import ZoneWindow
from not1mm.rotator import RotatorWindow
from not1mm.bandmap import BandMapWindow
from not1mm.vfo import VfoWindow
from not1mm.ratewindow import RateWindow
from not1mm.statistics import StatsWindow
from not1mm.chat import ChatWindow
from not1mm.radio import Radio
from not1mm.voice_keying import Voice
from not1mm.lookupservice import LookupService
from not1mm.rtc_service import RTCService
poll_time = datetime.datetime.now()
class MainWindow(QtWidgets.QMainWindow):
"""
The main window
"""
ctyfile = {}
pref_ref = {
"sounddevice": "default",
"useqrz": False,
"lookupusername": "username",
"lookuppassword": "password",
"run_state": True,
"command_buttons": False,
"cw_macros": True,
"bands_modes": True,
"bands": ["160", "80", "40", "20", "15", "10"],
"current_database": "ham.db",
"contest": "",
"multicast_group": "239.1.1.1",
"multicast_port": 2239,
"interface_ip": "0.0.0.0",
"send_rtc_scores": False,
"rtc_url": "",
"rtc_user": "",
"rtc_pass": "",
"rtc_interval": 2,
"send_n1mm_packets": False,
"n1mm_station_name": "20M CW Tent",
"n1mm_operator": "Bernie",
"n1mm_radioport": "127.0.0.1:12060",
"n1mm_contactport": "127.0.0.1:12060",
"n1mm_lookupport": "127.0.0.1:12060",
"n1mm_scoreport": "127.0.0.1:12060",
"usehamdb": False,
"usehamqth": False,
"cloudlog": False,
"cloudlogapi": "",
"cloudlogurl": "",
"CAT_ip": "127.0.0.1",
"userigctld": False,
"useflrig": False,
"cwip": "127.0.0.1",
"cwport": 6789,
"cwtype": 0,
"useserver": False,
"im_the_master": False,
"CAT_port": 4532,
"cluster_server": "dxc.nc7j.com",
"cluster_port": 7373,
"cluster_filter": "Set DX Filter SpotterCont=NA",
"cluster_mode": "OPEN",
"cluster_expire": 1,
"logwindow": False,
"bandmapwindow": False,
"checkwindow": False,
"vfowindow": False,
"ratewindow": False,
"statisticswindow": False,
"darkmode": True,
}
appstarted = False
contact = {}
contest = None
contest_settings = {}
contact_is_dupe = False
pref = {}
station = {}
spaceweather = ""
current_op = ""
current_mode = ""
current_band = ""
default_rst = "59"
cw = None
look_up = None
run_state = False
fkeys = {}
about_dialog = None
qrz_dialog = None
settings_dialog = None
edit_macro_dialog = None
contest_dialog = None
configuration_dialog = None
opon_dialog = None
rove_dialog = None
dbname = fsutils.USER_DATA_PATH, "/ham.db"
radio_state = {}
worked_list = {}
cw_entry_visible = False
last_focus = None
oldtext = ""
text_color = QColorConstants.Black
current_palette = None
use_esm = False
use_call_history = False
esm_dict = {}
sandpfreq = 0
current_sn = None
radio_thread = QThread()
voice_thread = QThread()
rtc_thread = QThread()
rig_control = None
log_window = None
check_window = None
bandmap_window = None
vfo_window = None
rate_window = None
statistics_window = None
dxcc_window = None
zone_window = None
rotator_window = None
voice_window = None
settings = None
lookup_service = None
fldigi_util = None
rtc_service = None
rtc_interval = 2
rtc_user = ""
rtc_url = ""
rtc_pass = ""
current_widget = None
auto_cq = False
auto_cq_then = datetime.datetime.now()
auto_cq_time = datetime.datetime.now()
auto_cq_delay = 15000
server_commands = []
def __init__(self, splash):
super().__init__()
logger.info("MainWindow: __init__")
self.splash = splash
self.dock_loc = {
"Top": Qt.DockWidgetArea.TopDockWidgetArea,
"Right": Qt.DockWidgetArea.RightDockWidgetArea,
"Left": Qt.DockWidgetArea.LeftDockWidgetArea,
"Bottom": Qt.DockWidgetArea.BottomDockWidgetArea,
}
self.setCorner(Qt.Corner.TopRightCorner, Qt.DockWidgetArea.RightDockWidgetArea)
self.setCorner(
Qt.Corner.BottomRightCorner, Qt.DockWidgetArea.RightDockWidgetArea
)
self.setCorner(Qt.Corner.TopLeftCorner, Qt.DockWidgetArea.LeftDockWidgetArea)
self.setCorner(Qt.Corner.BottomLeftCorner, Qt.DockWidgetArea.LeftDockWidgetArea)
self.fontfamily = self.load_fonts_from_dir(os.fspath(fsutils.APP_DATA_PATH))
uic.loadUi(fsutils.APP_DATA_PATH / "main.ui", self)
if sys.platform == "darwin":
QApplication.setStyle("Fusion")
def_font_size = 13
QApplication.instance().setFont(QFont(self.fontfamily, def_font_size))
self.F1.setFont(QFont(self.fontfamily, def_font_size))
self.F2.setFont(QFont(self.fontfamily, def_font_size))
self.F3.setFont(QFont(self.fontfamily, def_font_size))
self.F4.setFont(QFont(self.fontfamily, def_font_size))
self.F5.setFont(QFont(self.fontfamily, def_font_size))
self.F6.setFont(QFont(self.fontfamily, def_font_size))
self.F7.setFont(QFont(self.fontfamily, def_font_size))
self.F8.setFont(QFont(self.fontfamily, def_font_size))
self.F9.setFont(QFont(self.fontfamily, def_font_size))
self.F10.setFont(QFont(self.fontfamily, def_font_size))
self.F11.setFont(QFont(self.fontfamily, def_font_size))
self.F12.setFont(QFont(self.fontfamily, def_font_size))
self.radioButton_run.setFont(QFont(self.fontfamily, def_font_size))
self.radioButton_sp.setFont(QFont(self.fontfamily, def_font_size))
self.cw_speed.setFont(QFont(self.fontfamily, def_font_size))
self.callsign_label.setFont(QFont(self.fontfamily, def_font_size))
self.snt_label.setFont(QFont(self.fontfamily, def_font_size))
self.rcv_label.setFont(QFont(self.fontfamily, def_font_size))
self.other_label.setFont(QFont(self.fontfamily, def_font_size))
self.exch_label.setFont(QFont(self.fontfamily, def_font_size))
self.heading_distance.setFont(QFont(self.fontfamily, def_font_size))
self.history_info.setFont(QFont(self.fontfamily, def_font_size))
self.dx_entity.setFont(QFont(self.fontfamily, def_font_size))
self.score.setFont(QFont(self.fontfamily, def_font_size))
self.mults.setFont(QFont(self.fontfamily, def_font_size))
self.callsign.setFont(QFont(self.fontfamily, 20))
self.sent.setFont(QFont(self.fontfamily, 20))
self.receive.setFont(QFont(self.fontfamily, 20))
self.other_1.setFont(QFont(self.fontfamily, 20))
self.other_2.setFont(QFont(self.fontfamily, 20))
self.dupe_indicator.setFont(QFont(self.fontfamily, 20))
self.history_info.hide()
QApplication.instance().focusObjectChanged.connect(self.on_focus_changed)
QApplication.instance().styleHints().colorSchemeChanged.connect(
self.dark_watcher
)
self.dark_watcher(QApplication.instance().styleHints().colorScheme())
self.udp_fifo = queue.Queue()
self.server_message_watch_timer = QtCore.QTimer()
self.server_message_watch_timer.timeout.connect(self.check_udp_queue)
self.server_message_watch_timer.start(1000)
self.inputs_dict = {
self.callsign: "callsign",
self.sent: "sent",
self.receive: "receive",
self.other_1: "other_1",
self.other_2: "other_2",
}
self.cw_entry.hide()
self.leftdot.hide()
self.cwprogressBar.hide()
self.rightdot.hide()
self.n1mm = N1MM()
self.server_channel = Multicast(
multicast_group="239.1.1.1", multicast_port=2239, interface_ip="0.0.0.0"
)
self.server_channel.ready_read_connect(self.server_message)
self.ft8 = FT8Watcher()
self.ft8.set_callback(None)
self.mscp = SCP(fsutils.APP_DATA_PATH)
self.next_field = self.other_2
self.dupe_indicator.hide()
self.cw_speed.valueChanged.connect(self.cwspeed_spinbox_changed)
self.cw_entry.textChanged.connect(self.handle_text_change)
self.cw_entry.returnPressed.connect(self.toggle_cw_entry)
self.actionCW_Macros.triggered.connect(self.cw_macros_state_changed)
self.actionCommand_Buttons_2.triggered.connect(
self.command_buttons_state_change
)
self.actionLog_Window.triggered.connect(self.launch_log_window)
self.actionBandmap.triggered.connect(self.launch_bandmap_window)
self.actionCheck_Window.triggered.connect(self.launch_check_window)
self.actionRate_Window.triggered.connect(self.launch_rate_window)
self.actionStatistics.triggered.connect(self.launch_stats_window)
self.actionGroup_Chat.triggered.connect(self.launch_chat_window)
self.actionVFO.triggered.connect(self.launch_vfo)
self.actionDXCC.triggered.connect(self.launch_dxcc_window)
self.actionZone.triggered.connect(self.launch_zone_window)
self.actionRotator.triggered.connect(self.launch_rotator_window)
self.actionRecalculate_Mults.triggered.connect(self.recalculate_mults)
self.actionMark_Contacts_Dirty.triggered.connect(self.mark_all_dirty)
self.actionLoad_Call_History_File.triggered.connect(self.load_call_history)
self.actionGenerate_Cabrillo_ASCII.triggered.connect(
lambda x: self.generate_cabrillo("ascii")
)
self.actionGenerate_Cabrillo_UTF8.triggered.connect(
lambda x: self.generate_cabrillo("utf-8")
)
self.actionGenerate_ADIF.triggered.connect(self.generate_adif)
self.actionGenerate_EDI.triggered.connect(self.generate_edi)
self.actionImport_ADIF.triggered.connect(self.import_adif)
self.actionConfiguration_Settings.triggered.connect(
self.edit_configuration_settings
)
self.actionStationSettings.triggered.connect(self.edit_station_settings)
self.actionNew_Contest.triggered.connect(self.new_contest_dialog)
self.actionOpen_Contest.triggered.connect(self.open_contest)
self.actionEdit_Current_Contest.triggered.connect(self.edit_contest)
self.actionNew_Database.triggered.connect(self.new_database)
self.actionOpen_Database.triggered.connect(self.open_database)
self.actionEdit_Macros.triggered.connect(self.edit_macros)
self.actionAbout.triggered.connect(self.show_about_dialog)
self.actionHotKeys.triggered.connect(self.show_key_help)
self.actionHelp.triggered.connect(self.show_help_dialog)
self.actionUpdate_CTY.triggered.connect(self.check_for_new_cty)
self.actionUpdate_MASTER_SCP.triggered.connect(self.update_masterscp)
self.actionQuit.triggered.connect(self.quit_app)
self.radioButton_run.clicked.connect(self.run_sp_buttons_clicked)
self.radioButton_sp.clicked.connect(self.run_sp_buttons_clicked)
self.score.setText("0")
self.callsign.textEdited.connect(self.callsign_changed)
self.callsign.returnPressed.connect(self.check_esm_with_enter)
self.callsign.cursorPositionChanged.connect(self.check_esm)
self.sent.returnPressed.connect(self.check_esm_with_enter)
self.sent.cursorPositionChanged.connect(self.check_esm)
self.receive.returnPressed.connect(self.check_esm_with_enter)
self.receive.cursorPositionChanged.connect(self.check_esm)
self.other_1.returnPressed.connect(self.check_esm_with_enter)
self.other_1.textEdited.connect(self.other_1_changed)
self.other_1.cursorPositionChanged.connect(self.check_esm)
self.other_2.returnPressed.connect(self.check_esm_with_enter)
self.other_2.textEdited.connect(self.other_2_changed)
self.other_2.cursorPositionChanged.connect(self.check_esm)
self.sent.setText("59")
self.receive.setText("59")
icon_path = fsutils.APP_DATA_PATH
self.greendot = QtGui.QPixmap(str(icon_path / "greendot.png"))
self.reddot = QtGui.QPixmap(str(icon_path / "reddot.png"))
self.redserver = QtGui.QPixmap(str(icon_path / "cloud_red.png"))
self.greenserver = QtGui.QPixmap(str(icon_path / "cloud_green.png"))
self.leftdot.setPixmap(self.greendot)
self.rightdot.setPixmap(self.reddot)
self.radio_grey = QtGui.QPixmap(str(icon_path / "radio_grey.png"))
self.radio_red = QtGui.QPixmap(str(icon_path / "radio_red.png"))
self.radio_green = QtGui.QPixmap(str(icon_path / "radio_green.png"))
self.radio_icon.setPixmap(self.radio_grey)
self.log_it.clicked.connect(self.save_contact)
self.wipe.clicked.connect(self.clearinputs)
self.esc_stop.clicked.connect(self.stop_all)
self.mark.clicked.connect(lambda: self.mark_spot(f"{self.current_mode} MARKED"))
self.spot_it.clicked.connect(self.spot_dx)
self.F1.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F1.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F1))
self.F1.clicked.connect(lambda x: self.process_function_key(self.F1))
self.F2.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F2.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F2))
self.F2.clicked.connect(lambda x: self.process_function_key(self.F2))
self.F3.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F3.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F3))
self.F3.clicked.connect(lambda x: self.process_function_key(self.F3))
self.F4.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F4.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F4))
self.F4.clicked.connect(lambda x: self.process_function_key(self.F4))
self.F5.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F5.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F5))
self.F5.clicked.connect(lambda x: self.process_function_key(self.F5))
self.F6.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F6.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F6))
self.F6.clicked.connect(lambda x: self.process_function_key(self.F6))
self.F7.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F7.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F7))
self.F7.clicked.connect(lambda x: self.process_function_key(self.F7))
self.F8.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F8.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F8))
self.F8.clicked.connect(lambda x: self.process_function_key(self.F8))
self.F9.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F9.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F9))
self.F9.clicked.connect(lambda x: self.process_function_key(self.F9))
self.F10.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F10.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F10))
self.F10.clicked.connect(lambda x: self.process_function_key(self.F10))
self.F11.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F11.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F11))
self.F11.clicked.connect(lambda x: self.process_function_key(self.F11))
self.F12.setContextMenuPolicy(QtCore.Qt.ContextMenuPolicy.CustomContextMenu)
self.F12.customContextMenuRequested.connect(lambda x: self.edit_macro(self.F12))
self.F12.clicked.connect(lambda x: self.process_function_key(self.F12))
self.cw_band_160.mousePressEvent = lambda x: self.change_to_band_and_mode(
160, "CW"
)
self.cw_band_80.mousePressEvent = lambda x: self.change_to_band_and_mode(
80, "CW"
)
self.cw_band_60.mousePressEvent = lambda x: self.change_to_band_and_mode(
60, "CW"
)
self.cw_band_40.mousePressEvent = lambda x: self.change_to_band_and_mode(
40, "CW"
)
self.cw_band_30.mousePressEvent = lambda x: self.change_to_band_and_mode(
30, "CW"
)
self.cw_band_20.mousePressEvent = lambda x: self.change_to_band_and_mode(
20, "CW"
)
self.cw_band_17.mousePressEvent = lambda x: self.change_to_band_and_mode(
17, "CW"
)
self.cw_band_15.mousePressEvent = lambda x: self.change_to_band_and_mode(
15, "CW"
)
self.cw_band_12.mousePressEvent = lambda x: self.change_to_band_and_mode(
12, "CW"
)
self.cw_band_10.mousePressEvent = lambda x: self.change_to_band_and_mode(
10, "CW"
)
self.cw_band_6.mousePressEvent = lambda x: self.change_to_band_and_mode(6, "CW")
self.cw_band_4.mousePressEvent = lambda x: self.change_to_band_and_mode(4, "CW")
self.cw_band_2.mousePressEvent = lambda x: self.change_to_band_and_mode(2, "CW")
self.cw_band_125.mousePressEvent = lambda x: self.change_to_band_and_mode(
222, "CW"
)
self.cw_band_70cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
432, "CW"
)
self.cw_band_33cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
902, "CW"
)
self.cw_band_23cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
1240, "CW"
)
self.ssb_band_160.mousePressEvent = lambda x: self.change_to_band_and_mode(
160, "SSB"
)
self.ssb_band_80.mousePressEvent = lambda x: self.change_to_band_and_mode(
80, "SSB"
)
self.ssb_band_60.mousePressEvent = lambda x: self.change_to_band_and_mode(
60, "SSB"
)
self.ssb_band_40.mousePressEvent = lambda x: self.change_to_band_and_mode(
40, "SSB"
)
self.ssb_band_20.mousePressEvent = lambda x: self.change_to_band_and_mode(
20, "SSB"
)
self.ssb_band_17.mousePressEvent = lambda x: self.change_to_band_and_mode(
17, "SSB"
)
self.ssb_band_15.mousePressEvent = lambda x: self.change_to_band_and_mode(
15, "SSB"
)
self.ssb_band_12.mousePressEvent = lambda x: self.change_to_band_and_mode(
12, "SSB"
)
self.ssb_band_10.mousePressEvent = lambda x: self.change_to_band_and_mode(
10, "SSB"
)
self.ssb_band_6.mousePressEvent = lambda x: self.change_to_band_and_mode(
6, "SSB"
)
self.ssb_band_4.mousePressEvent = lambda x: self.change_to_band_and_mode(
4, "SSB"
)
self.ssb_band_2.mousePressEvent = lambda x: self.change_to_band_and_mode(
2, "SSB"
)
self.ssb_band_125.mousePressEvent = lambda x: self.change_to_band_and_mode(
222, "SSB"
)
self.ssb_band_70cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
432, "SSB"
)
self.ssb_band_33cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
902, "SSB"
)
self.ssb_band_23cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
1240, "SSB"
)
self.rtty_band_160.mousePressEvent = lambda x: self.change_to_band_and_mode(
160, "RTTY"
)
self.rtty_band_80.mousePressEvent = lambda x: self.change_to_band_and_mode(
80, "RTTY"
)
self.rtty_band_60.mousePressEvent = lambda x: self.change_to_band_and_mode(
60, "RTTY"
)
self.rtty_band_40.mousePressEvent = lambda x: self.change_to_band_and_mode(
40, "RTTY"
)
self.rtty_band_30.mousePressEvent = lambda x: self.change_to_band_and_mode(
30, "RTTY"
)
self.rtty_band_20.mousePressEvent = lambda x: self.change_to_band_and_mode(
20, "RTTY"
)
self.rtty_band_17.mousePressEvent = lambda x: self.change_to_band_and_mode(
17, "RTTY"
)
self.rtty_band_15.mousePressEvent = lambda x: self.change_to_band_and_mode(
15, "RTTY"
)
self.rtty_band_12.mousePressEvent = lambda x: self.change_to_band_and_mode(
12, "RTTY"
)
self.rtty_band_10.mousePressEvent = lambda x: self.change_to_band_and_mode(
10, "RTTY"
)
self.rtty_band_6.mousePressEvent = lambda x: self.change_to_band_and_mode(
6, "RTTY"
)
self.rtty_band_4.mousePressEvent = lambda x: self.change_to_band_and_mode(
4, "RTTY"
)
self.rtty_band_2.mousePressEvent = lambda x: self.change_to_band_and_mode(
2, "RTTY"
)
self.rtty_band_125.mousePressEvent = lambda x: self.change_to_band_and_mode(
222, "RTTY"
)
self.rtty_band_70cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
432, "RTTY"
)
self.rtty_band_33cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
902, "RTTY"
)
self.rtty_band_23cm.mousePressEvent = lambda x: self.change_to_band_and_mode(
1240, "RTTY"
)
self.band_indicators_cw = {
"160": self.cw_band_160,
"80": self.cw_band_80,
"60": self.cw_band_60,
"40": self.cw_band_40,
"30": self.cw_band_30,
"20": self.cw_band_20,
"17": self.cw_band_17,
"15": self.cw_band_15,
"12": self.cw_band_12,
"10": self.cw_band_10,
"6": self.cw_band_6,
"4": self.cw_band_4,
"2": self.cw_band_2,
"1.25": self.cw_band_125,
"70cm": self.cw_band_70cm,
"33cm": self.cw_band_33cm,
"23cm": self.cw_band_23cm,
}
self.band_indicators_ssb = {
"160": self.ssb_band_160,
"80": self.ssb_band_80,
"60": self.ssb_band_60,
"40": self.ssb_band_40,
"20": self.ssb_band_20,
"17": self.ssb_band_17,
"15": self.ssb_band_15,
"12": self.ssb_band_12,
"10": self.ssb_band_10,
"6": self.ssb_band_6,
"4": self.ssb_band_4,
"2": self.ssb_band_2,
"1.25": self.ssb_band_125,
"70cm": self.ssb_band_70cm,
"33cm": self.ssb_band_33cm,
"23cm": self.ssb_band_23cm,
}
self.band_indicators_rtty = {
"160": self.rtty_band_160,
"80": self.rtty_band_80,
"60": self.rtty_band_60,
"40": self.rtty_band_40,
"30": self.rtty_band_30,
"20": self.rtty_band_20,
"17": self.rtty_band_17,
"15": self.rtty_band_15,
"12": self.rtty_band_12,
"10": self.rtty_band_10,
"6": self.rtty_band_6,
"4": self.rtty_band_4,
"2": self.rtty_band_2,
"1.25": self.rtty_band_125,
"70cm": self.rtty_band_70cm,
"33cm": self.rtty_band_33cm,
"23cm": self.rtty_band_23cm,
}
self.all_mode_indicators = {
"CW": self.band_indicators_cw,
"SSB": self.band_indicators_ssb,
"RTTY": self.band_indicators_rtty,
}
self.setWindowIcon(
QtGui.QIcon(str(fsutils.APP_DATA_PATH / "k6gte.not1mm-32.png"))
)
self.show_splash_msg("Loading CTY file.")
try:
with open(
fsutils.APP_DATA_PATH / "cty.json", "rt", encoding="utf-8"
) as c_file:
self.ctyfile = loads(c_file.read())
except (IOError, JSONDecodeError, TypeError):
logging.critical("There was an error parsing the BigCity file.")
self.show_splash_msg("Starting LookUp Service.")
self.lookup_service = LookupService()
self.lookup_service.message.connect(self.dockwidget_message)
self.lookup_service.hide()
self.server_seen = datetime.datetime.now()
self.show_splash_msg("Reading preferences.")
self.readpreferences()
self.show_splash_msg("Starting voice thread.")
self.voice_process = Voice()
self.voice_process.moveToThread(self.voice_thread)
self.voice_thread.started.connect(self.voice_process.run)
self.voice_thread.finished.connect(self.voice_process.deleteLater)
self.voice_process.ptt_on.connect(self.ptt_on)
self.voice_process.ptt_off.connect(self.ptt_off)
self.voice_process.current_op = self.current_op
self.voice_process.data_path = fsutils.USER_DATA_PATH
self.voice_process.sounddevice = self.pref.get("sounddevice", "default")
self.voice_thread.start()
self.dbname = fsutils.USER_DATA_PATH / self.pref.get(
"current_database", "ham.db"
)
self.database = DataBase(self.dbname, fsutils.APP_DATA_PATH)
self.station = self.database.fetch_station()
if self.station is None:
self.station = {}
self.edit_station_settings()
self.station = self.database.fetch_station()
if self.station is None:
self.station = {}
if self.rotator_window is not None:
self.rotator_window.set_mygrid(self.station.get("GridSquare", ""))
self.contact = self.database.empty_contact.copy()
self.previous_contact = (
self.contact
) # Keep previous contact, if any, so we can spot it.
self.current_op = self.station.get("Call", "")
self.voice_process.current_op = self.current_op
self.make_op_dir()
self.cq_freq = None
logger.debug(f"{QT_VERSION_STR=} {PYQT_VERSION_STR=}")
x = PYQT_VERSION_STR.split(".")
old_Qt = True
# test if pyqt version is at least 6.8
if len(x) == 1:
if int(x[0]) > 6:
old_Qt = False
elif len(x) >= 2:
if int(x[0]) >= 6 and int(x[1]) >= 8:
old_Qt = False
# Featureset for wayland if pyqt is older than 6.8
dockfeatures = (
QtWidgets.QDockWidget.DockWidgetFeature.DockWidgetClosable
| QtWidgets.QDockWidget.DockWidgetFeature.DockWidgetMovable
)
self.show_splash_msg("Setting up BandMapWindow.")
self.bandmap_window = BandMapWindow(self.actionBandmap)
self.bandmap_window.setObjectName("bandmap-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.bandmap_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.LeftDockWidgetArea, self.bandmap_window)
self.bandmap_window.hide()
self.bandmap_window.cluster_expire.connect(self.cluster_expire_updated)
self.bandmap_window.message.connect(self.dockwidget_message)
self.bandmap_window.callsignField.setText(self.current_op)
self.bandmap_window.bandmapwindow_closed.connect(self.launch_bandmap_window)
self.show_splash_msg("Setting up CheckWindow.")
self.check_window = CheckWindow(self.actionCheck_Window)
self.check_window.setObjectName("check-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.check_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.check_window)
self.check_window.hide()
self.check_window.message.connect(self.dockwidget_message)
self.check_window.checkwindow_closed.connect(self.launch_check_window)
self.show_splash_msg("Setting up RateWindow.")
self.rate_window = RateWindow(self.actionRate_Window)
self.rate_window.setObjectName("rate-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.rate_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.rate_window)
self.rate_window.hide()
self.rate_window.message.connect(self.dockwidget_message)
self.rate_window.ratewindow_closed.connect(self.launch_rate_window)
self.show_splash_msg("Setting up StatisticsWindow.")
self.statistics_window = StatsWindow(self.actionStatistics)
self.statistics_window.setObjectName("statistics-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.statistics_window.setFeatures(dockfeatures)
self.addDockWidget(
Qt.DockWidgetArea.RightDockWidgetArea, self.statistics_window
)
self.statistics_window.hide()
self.statistics_window.message.connect(self.dockwidget_message)
self.statistics_window.statisticswindow_closed.connect(self.launch_stats_window)
self.show_splash_msg("Setting up GroupChatWindow.")
self.chat_window = ChatWindow(self.actionGroup_Chat)
self.chat_window.setObjectName("chat-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.chat_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.chat_window)
self.chat_window.hide()
self.chat_window.message.connect(self.dockwidget_message)
self.chat_window.mycall = self.current_op
self.chat_window.chatwindow_closed.connect(self.launch_chat_window)
self.show_splash_msg("Setting up DXCCWindow.")
self.dxcc_window = DXCCWindow(self.actionDXCC)
self.dxcc_window.setObjectName("dxcc-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.dxcc_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.dxcc_window)
self.dxcc_window.hide()
self.dxcc_window.message.connect(self.dockwidget_message)
self.dxcc_window.dxcc_trackerwindow_closed.connect(self.launch_dxcc_window)
self.show_splash_msg("Setting up ZoneWindow.")
self.zone_window = ZoneWindow(self.actionZone)
self.zone_window.setObjectName("zone-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.zone_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.zone_window)
self.zone_window.hide()
self.zone_window.message.connect(self.dockwidget_message)
self.zone_window.zone_trackerwindow_closed.connect(self.launch_zone_window)
self.show_splash_msg("Setting up RotatorWindow.")
self.rotator_window = RotatorWindow(
self.actionRotator,
host=self.pref.get("rotctld_address", "127.0.0.1"),
port=self.pref.get("rotctld_port", 4533),
)
self.rotator_window.setObjectName("rotator-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.rotator_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.rotator_window)
self.rotator_window.hide()
self.rotator_window.message.connect(self.dockwidget_message)
self.rotator_window.set_mygrid(self.station.get("GridSquare", ""))
self.rotator_window.rotatorwindow_closed.connect(self.launch_rotator_window)
self.show_splash_msg("Setting up VFOWindow.")
self.vfo_window = VfoWindow(self.actionVFO)
self.vfo_window.setObjectName("vfo-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.vfo_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.RightDockWidgetArea, self.vfo_window)
self.vfo_window.hide()
self.vfo_window.vfowindow_closed.connect(self.launch_vfo)
self.show_splash_msg("Setting up LogWindow.")
self.log_window = LogWindow(self.actionLog_Window)
self.log_window.setObjectName("log-window")
if os.environ.get("WAYLAND_DISPLAY") and old_Qt is True:
self.log_window.setFeatures(dockfeatures)
self.addDockWidget(Qt.DockWidgetArea.TopDockWidgetArea, self.log_window)
self.log_window.hide()
self.log_window.message.connect(self.dockwidget_message)
self.log_window.logwindow_closed.connect(self.launch_log_window)
self.clearinputs()
self.show_splash_msg("Loading contest.")
self.load_contest()
self.show_splash_msg("Reading macros.")
self.read_macros()
self.show_splash_msg("Restoring window states.")
self.settings = QSettings("K6GTE", "not1mm")
if self.settings.value("windowState") is not None:
self.restoreState(self.settings.value("windowState"))
if self.settings.value("geometry") is not None:
self.restoreGeometry(self.settings.value("geometry"))
self.actionLog_Window.setChecked(self.pref.get("logwindow", False))
if self.actionLog_Window.isChecked():
self.log_window.show()
else:
self.log_window.hide()
self.actionBandmap.setChecked(self.pref.get("bandmapwindow", False))
if self.actionBandmap.isChecked():
self.bandmap_window.show()
self.bandmap_window.setActive(True)
else:
self.bandmap_window.hide()
self.bandmap_window.setActive(False)
self.actionGroup_Chat.setChecked(self.pref.get("chatwindow", False))
if self.actionGroup_Chat.isChecked():
self.chat_window.show()
self.chat_window.setActive(True)
else:
self.chat_window.hide()
self.chat_window.setActive(False)
self.actionCheck_Window.setChecked(self.pref.get("checkwindow", False))
if self.actionCheck_Window.isChecked():
self.check_window.show()
self.check_window.setActive(True)
else:
self.check_window.hide()
self.check_window.setActive(False)
self.actionRate_Window.setChecked(self.pref.get("ratewindow", False))
if self.actionRate_Window.isChecked():
self.rate_window.show()
self.rate_window.setActive(True)
else:
self.rate_window.hide()
self.rate_window.setActive(False)
self.actionStatistics.setChecked(self.pref.get("statisticswindow", False))
if self.actionStatistics.isChecked():
self.statistics_window.show()
self.statistics_window.setActive(True)
self.statistics_window.get_run_and_total_qs()
else:
self.statistics_window.hide()
self.statistics_window.setActive(False)
self.actionDXCC.setChecked(self.pref.get("dxccwindow", False))
if self.actionDXCC.isChecked():
self.dxcc_window.show()
self.dxcc_window.setActive(True)
self.dxcc_window.get_log()
else:
self.dxcc_window.hide()
self.dxcc_window.setActive(False)
self.actionZone.setChecked(self.pref.get("zonewindow", False))
if self.actionZone.isChecked():
self.zone_window.show()
self.zone_window.setActive(True)
self.zone_window.get_log()
else:
self.zone_window.hide()
self.zone_window.setActive(False)
self.actionRotator.setChecked(self.pref.get("rotatorwindow", False))
if self.actionRotator.isChecked():
self.rotator_window.show()
self.rotator_window.setActive(True)
else:
self.rotator_window.hide()
self.rotator_window.setActive(False)
self.actionVFO.setChecked(self.pref.get("vfowindow", False))
if self.actionVFO.isChecked():
self.vfo_window.show()
else:
self.vfo_window.hide()
self.cwspeed_spinbox_changed()
if not DEBUG_ENABLED:
if VersionTest(__version__).test():
self.show_message_box(
"There is a newer version of not1mm available.\n"
"You can update to the current version by using:\n\n"
"pip install -U not1mm\n\tor\n"
"pipx upgrade not1mm\n\tor\n"
"uv tool install not1mm@latest",
blocking=False,
)
self.udp_socket = QtNetwork.QUdpSocket()
b_result = self.udp_socket.bind(
QtNetwork.QHostAddress.SpecialAddress.AnyIPv4, 9876
)
logger.info(f"bind {b_result}")
self.udp_socket.readyRead.connect(self.fldigi_on_udp_socket_ready_read)
self.resolve_dirty_records()
self.dark_watcher(QApplication.instance().styleHints().colorScheme())
# Server stuff
def resolve_dirty_records(self) -> None:
"""Go through dirty records and submit them to the server queue."""
if (
self.pref.get("useserver", False) is True
and hasattr(self, "database")
and datetime.datetime.now() < self.server_seen
):
records = self.database.fetch_all_dirty_contacts()
print(f"Resolving {len(records)} unsent contacts.\n")
if records:
for contact in records:
contact["cmd"] = "POST"
stale = datetime.datetime.now() + datetime.timedelta(seconds=30)
contact["expire"] = stale.isoformat()
self.server_commands.append(contact)
def clear_dirty_flag(self, unique_id: str) -> None:
"""clear the dirty flag on record once response is returned from server."""
self.database.clear_dirty_flag(unique_id)
# show_dirty_records()
def remove_confirmed_commands(self, data: dict) -> None:
"""Removed confirmed commands from the sent commands list."""
for index, item in enumerate(self.server_commands):
if item.get("ID") == data.get("unique_id") and item.get("cmd") == data.get(
"subject"
):
self.server_commands.pop(index)
self.clear_dirty_flag(data.get("unique_id"))
def check_for_stale_commands(self) -> None:
"""
Check through server commands to see if there has not been a reply in 30 seconds.
Resubmits those that are stale.
"""
if self.pref.get("useserver", False) is True:
for index, item in enumerate(self.server_commands):
expired = datetime.datetime.strptime(
item.get("expire"), "%Y-%m-%dT%H:%M:%S.%f"
)
if datetime.datetime.now() > expired:
newexpire = datetime.datetime.now() + datetime.timedelta(seconds=30)
self.server_commands[index]["expire"] = newexpire.isoformat()
try:
self.server_channel.send_as_json(self.server_commands[index])
except OSError as err:
logging.warning("%s", err)
def server_message(self) -> None:
msg = self.server_channel.getpacket()
if msg:
self.udp_fifo.put(msg)
def check_udp_queue(self) -> None:
"""checks the UDP datagram queue."""
self.check_for_stale_commands()
while not self.udp_fifo.empty():
datagram = self.udp_fifo.get()
try:
json_data = loads(datagram.decode())
except UnicodeDecodeError as err:
the_error = f"Not Unicode: {err}\n{datagram}"
logger.info(the_error)
continue
except JSONDecodeError as err:
the_error = f"Not JSON: {err}\n{datagram}"
logger.info(the_error)
continue
logger.info("%s", json_data)
if json_data.get("cmd") == "PING":
if json_data.get("host"):
self.server_seen = datetime.datetime.now() + datetime.timedelta(
seconds=15
)
self.server_icon.setPixmap(self.greenserver)
continue
if json_data.get("cmd") == "CONTEST_REQUEST":
if (
self.pref.get("useserver", False) is True
and self.pref.get("im_the_master", False) is True
):
cmd = self.contest_settings.copy()
cmd["cmd"] = "NEWDB"
stale = datetime.datetime.now() + datetime.timedelta(seconds=30)
cmd["expire"] = stale.isoformat()
cmd["NetBiosName"] = socket.gethostname()
cmd["Operator"] = self.current_op
cmd["ID"] = uuid.uuid4().hex
cmd["Station"] = self.station
try:
self.server_channel.send_as_json(cmd)
except OSError as err:
logging.warning("%s", err)
continue
if json_data.get("cmd") == "RESPONSE":
if json_data.get("recipient") == socket.gethostname():
if json_data.get("subject") == "GET_SN":
# {
# "cmd": "RESPONSE",
# "recipient": "NetBiosName",
# "subject": "GET_SN",
# "sn": int or None,
# }
self.current_sn = json_data.get("sn")
continue
if json_data.get("subject") == "HOSTINFO":
# self.groupcall = json_data.get("groupcall", "")
# self.myclassEntry.setText(str(json_data.get("groupclass", "")))
# self.mysectionEntry.setText(
# str(json_data.get("groupsection", ""))
# )
# self.group_call_indicator.setText(self.groupcall.center(14))
# self.changemyclass()
# self.changemysection()
# self.mycallEntry.hide()
# self.server_seen = datetime.now() + timedelta(seconds=30)
# self.group_call_indicator.setStyleSheet(
# "border: 1px solid green;"
# )
return
if json_data.get("subject") == "LOG":
...
# self.infoline.setText("Server Generated Log.")
if json_data.get("subject") == "ISDUPE":
# TODO
result = json_data.get("isdupe", False)
self.contact_is_dupe = result
if result is not False:
self.dupe_indicator.show()
self.callsign.setStyleSheet("color: red;")
else:
self.dupe_indicator.hide()
self.callsign.setStyleSheet("")
if json_data.get("subject") == "POST":
self.remove_confirmed_commands(json_data)
if json_data.get("subject") == "DELETE":
self.remove_confirmed_commands(json_data)
if json_data.get("subject") == "CONTACTCHANGED":
self.remove_confirmed_commands(json_data)
if json_data.get("subject") == "NEWDB":
self.remove_confirmed_commands(json_data)
continue
if json_data.get("cmd") == "CHAT":
# print(f"Got {json_data.get('cmd')} {json_data=}")
# self.display_chat(json_data.get("sender"), json_data.get("message"))
# {"cmd": "CHAT", "sender": "N2CQR", "message": "I worked your mama on 80 meters."}
self.chat_window.msg_from_main(json_data)
continue
if json_data.get("cmd") == "GROUPQUERY":
...
# print(f"Got {json_data.get('cmd')} {json_data=}")
# if self.groupcall:
# self.send_status_udp()
def fldigi_on_udp_socket_ready_read(self) -> None:
""""""
datagram, sender_host, sender_port_number = self.udp_socket.readDatagram(
self.udp_socket.pendingDatagramSize()
)
print(f"{datagram=}")
self.fldigi_qso(datagram.decode())
def is_it_dark(self) -> bool:
"""Returns if the DE has a dark theme active."""
hints = QtGui.QGuiApplication.styleHints()
scheme = hints.colorScheme()
return scheme == Qt.ColorScheme.Dark
def dark_watcher(self, color_scheme: Qt.ColorScheme):
"""..."""
self.setDarkMode(setdarkmode=color_scheme == Qt.ColorScheme.Dark)
def load_call_history(self) -> None:
"""Display filepicker and load chosen call history file."""
filename = self.filepicker("other")
if filename:
self.database.create_callhistory_table()
self.database.delete_callhistory()
try:
with open(filename, "rt", encoding="utf-8") as file_descriptor:
lines = file_descriptor.readlines()
substring_to_find = "!!Order!!"
found_index = -1 # Initialize to -1 to indicate not found
for index, item in enumerate(lines):
if substring_to_find in item:
found_index = index
break # Exit the loop once found
if found_index != -1:
item_names = lines[found_index].strip().split(",")
# ['!!Order!!', 'Call', 'Sect', 'State', 'CK', 'UserText', '']
item_names = item_names[1:]
# ['Call', 'Sect', 'State', 'CK', 'UserText', '']
lines = lines[found_index + 1 :]
group_list = []
for line in lines:
if line.startswith("#"):
continue
group = {}
fields = line.strip().split(",")
# ['4U1WB','MDC','DC','89','']
number_of_fields = len(fields)
count = 0
try:
for item in item_names:
if item == "":
continue
if count < number_of_fields:
group[item] = fields[count]
else:
group[item] = ""
count += 1
group_list.append(group)
except IndexError:
...
self.database.add_callhistory_items(group_list)
except FileNotFoundError as err:
self.show_message_box(f"{err}", blocking=False)
def on_focus_changed(self, focused_widget: QtWidgets.QWidget):
"""Called when text entry focus has changed."""
if self.use_esm:
if hasattr(self.contest, "process_esm"):
self.contest.process_esm(self, new_focused_widget=focused_widget)
def make_button_blue(self, the_button: QtWidgets.QPushButton) -> None:
"""Takes supplied QPushButton object and turns it blue."""
if the_button is not None:
pal = QPalette()
pal.isCopyOf(self.current_palette)
blueColor = QColor(0, 0, 128)
pal.setBrush(QPalette.ColorRole.Button, blueColor)
the_button.setPalette(pal)
def make_button_green(self, the_button: QtWidgets.QPushButton) -> None:
"""Takes supplied QPushButton object and turns it green."""
if the_button is not None:
pal = QPalette()
pal.isCopyOf(self.current_palette)
greenColor = QColor(127, 127, 0)
pal.setBrush(QPalette.ColorRole.Button, greenColor)
the_button.setPalette(pal)
def restore_button_color(self, the_button: QtWidgets.QPushButton) -> None:
"""Restores the color of the button"""
the_button.setPalette(self.current_palette)
def check_esm_with_enter(self) -> None:
"""Check for ESM, otherwise save contact."""
if self.use_esm:
if hasattr(self.contest, "process_esm"):
self.contest.process_esm(self, with_enter=True)
else:
self.save_contact()
else:
self.save_contact()
def check_esm(self) -> None:
"""Check for ESM, otherwise save contact."""
if self.use_esm:
if hasattr(self.contest, "process_esm"):
self.contest.process_esm(self)
else:
...
# self.save_contact()
else:
...
# self.save_contact()
def show_splash_msg(self, msg: str) -> None:
"""Show text message in the splash window."""
self.splash.showMessage(
msg,
alignment=Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignCenter,
color=QColor(255, 255, 0),
)
QCoreApplication.processEvents()
def dockwidget_message(self, msg: dict) -> None:
"""incomming signals from widgets"""
if msg:
# Pass delete message from log window to server.
if msg.get("cmd", "") == "DELETED":
if self.pref.get("useserver", False) is True:
stale = datetime.datetime.now() + datetime.timedelta(seconds=30)
msg["cmd"] = "DELETE"
msg["expire"] = stale.isoformat()
msg["station"] = socket.gethostname()
msg["unique_id"] = msg.get("ID")
self.server_commands.append(msg)
try:
self.server_channel.send_as_json(msg)
except OSError as err:
logging.warning("%s", err)
if msg.get("cmd", "") == "CONTACTCHANGED":
if self.pref.get("useserver", False) is True:
stale = datetime.datetime.now() + datetime.timedelta(seconds=30)
msg["expire"] = stale.isoformat()
msg["station"] = socket.gethostname()
msg["unique_id"] = msg.get("ID")
self.server_commands.append(msg)
try:
self.server_channel.send_as_json(msg)
except OSError as err:
logging.warning("%s", err)
# TODO
if msg.get("cmd", "") in ["CONTACTCHANGED", "DELETE", "DELETED"]:
if self.statistics_window:
self.statistics_window.msg_from_main(msg)
if self.dxcc_window:
self.dxcc_window.msg_from_main(msg)
if self.zone_window:
self.zone_window.msg_from_main(msg)
if self.rate_window:
self.rate_window.msg_from_main(msg)
self.check_dupe(self.callsign.text())
if msg.get("cmd", "") == "GETCOLUMNS":
if hasattr(self.contest, "columns"):
cmd = {}
cmd["cmd"] = "SHOWCOLUMNS"
cmd["COLUMNS"] = self.contest.columns
if self.log_window:
self.log_window.msg_from_main(cmd)
return
if msg.get("cmd", "") == "TUNE":
# b'{"cmd": "TUNE", "freq": 7.0235, "spot": "MM0DGI"}'
self.clearinputs()
if self.vfo_window:
self.vfo_window.msg_from_main(msg)
vfo = msg.get("freq")
vfo = float(vfo) * 1000
self.radio_state["vfoa"] = int(vfo)
if self.rig_control:
self.rig_control.set_vfo(int(vfo))
spot = msg.get("spot", "")
if spot == "CQ": # saved CQ frequency, switch to RUN
self.clearinputs()
self.set_running(True)
return
self.callsign.setText(spot)
self.callsign_changed()
self.callsign.setFocus()
self.callsign.activateWindow()
self.set_running(False)
return
if msg.get("cmd", "") == "GETWORKEDLIST":
result = self.database.get_calls_and_bands()
cmd = {}
cmd["cmd"] = "WORKED"
cmd["worked"] = result
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
return
if msg.get("cmd", "") == "GETCONTESTSTATUS":
cmd = {
"cmd": "CONTESTSTATUS",
"contest": self.contest_settings,
"operator": self.current_op,
}
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
self.bandmap_window.callsignField.setText(self.current_op)
if self.chat_window:
self.chat_window.msg_from_main(cmd)
self.chat_window.mycall = self.current_op
return
if msg.get("cmd", "") == "CHANGECALL":
self.activateWindow()
self.callsign.setText(msg.get("call", ""))
self.callsign.setFocus()
self.callsign_changed()
if msg.get("cmd", "") == "CHECKSPOTS":
if self.check_window:
msg["call"] = self.callsign.text()
self.check_window.msg_from_main(msg)
# '{"cmd": "LOOKUP_RESPONSE", "station": "fredo", "result": {"call": "K6GTE", "aliases": "KM6HQI", "dxcc": "291", "nickname": "Mike", "fname": "Michael C", "name": "Bridak", "addr1": "2854 W Bridgeport Ave", "addr2": "Anaheim", "state": "CA", "zip": "92804", "country": "United States", "lat": "33.825460", "lon": "-117.987510", "grid": "DM13at", "county": "Orange", "ccode": "271", "fips": "06059", "land": "United States", "efdate": "2021-01-13", "expdate": "2027-11-07", "class": "G", "codes": "HVIE", "email": "michael.bridak@gmail.com", "u_views": "3049", "bio": "7232", "biodate": "2023-04-10 17:56:55", "image": "https://cdn-xml.qrz.com/e/k6gte/qsl.png", "imageinfo": "285:545:99376", "moddate": "2021-04-08 21:41:07", "MSA": "5945", "AreaCode": "714", "TimeZone": "Pacific", "GMTOffset": "-8", "DST": "Y", "eqsl": "0", "mqsl": "1", "cqzone": "3", "ituzone": "6", "born": "1967", "lotw": "1", "user": "K6GTE", "geoloc": "geocode", "name_fmt": "Michael C \\"Mike\\" Bridak"}}'
if msg.get("cmd", "") == "LOOKUP_RESPONSE":
if msg.get("result", None) is not None:
fname = msg.get("result", {}).get("fname", "")
name = msg.get("result", {}).get("name", "")
grid = msg.get("result", {}).get("grid", "")
nickname = msg.get("result", {}).get("nickname", "")
if self.contest:
if "General Logging" in self.contest.name:
if nickname:
self.other_1.setText(nickname)
elif fname:
self.other_1.setText(fname)
elif name:
self.other_1.setText(name)
if isinstance(grid, str) and len(grid) > 0:
self.contact["GridSquare"] = grid
if self.station.get("GridSquare", ""):
heading = bearing(self.station.get("GridSquare", ""), grid)
kilometers = distance(
self.station.get("GridSquare", ""), grid
)
self.heading_distance.setText(
f"{grid} Hdg {heading}° LP {reciprocal(heading)}° / "
f"distance {int(kilometers*0.621371)}mi {kilometers}km"
f" {msg.get('result', {}).get('name_fmt', '')}"
)
self.rotator_window.set_requested_azimuth(float(heading))
if msg.get("cmd", "") == "CHAT":
if self.pref.get("useserver", False) is True:
msg["sender"] = self.current_op
try:
self.server_channel.send_as_json(msg)
except OSError as err:
logging.warning("%s", err)
return
if msg.get("cmd", "") == "SPACEWEATHER":
# cmd["cmd"] = "SPACEWEATHER"
# cmd["date"] = match.group(1)
# cmd["hour"] = match.group(2)
# cmd["sfi"] = match.group(3)
# cmd["aindex"] = match.group(4)
# cmd["kindex"] = match.group(5)
# cmd["conditions"] = match.group(6).strip()
# cmd["source"] = match.group(7)
self.spaceweather = f"SFI: {msg.get('sfi', '')} A: {msg.get('aindex', '')} K: {msg.get('kindex', '')}"
self.set_window_title()
def cluster_expire_updated(self, number: str) -> None:
"""signal from bandmap"""
self.pref["cluster_expire"] = int(number)
self.write_preference()
def fldigi_qso(self, result: str) -> None:
"""
gets called when there is a new fldigi qso logged.
{
'FREQ': '7.029500',
'CALL': 'DL2DSL',
'MODE': 'RTTY',
'NAME': 'BOB',
'QSO_DATE': '20240904',
'QSO_DATE_OFF': '20240904',
'TIME_OFF': '212825',
'TIME_ON': '212800',
'RST_RCVD': '599',
'RST_SENT': '599',
'BAND': '40M',
'COUNTRY': 'FED. REP. OF GERMANY',
'CQZ': '14',
'STX': '000',
'STX_STRING': '1D ORG',
'CLASS': '1D',
'ARRL_SECT': 'DX',
'TX_PWR': '0',
'OPERATOR': 'K6GTE',
'STATION_CALLSIGN': 'K6GTE',
'MY_GRIDSQUARE': 'DM13AT',
'MY_CITY': 'ANAHEIM, CA',
'MY_STATE': 'CA'
}
"""
if result and result != "NONE":
datadict = {}
splitdata = result.upper().strip().split("<")
try:
for data in splitdata:
if data:
tag = data.split(":")
if tag == ["EOR>"]:
break
datadict[tag[0]] = tag[1].split(">")[1].strip()
except IndexError:
logger.debug(f"Parse error: {result=} {data=} {tag=}")
logger.debug(f"{datadict=}")
print(f"{datadict=}")
if hasattr(self.contest, "ft8_handler"):
self.contest.set_self(self)
self.contest.ft8_handler(datadict)
def setDarkMode(self, setdarkmode=False) -> None:
"""Forces a darkmode palette."""
logger.debug(f"Dark mode set to: {setdarkmode}")
cmd = {}
cmd["cmd"] = "DARKMODE"
cmd["state"] = setdarkmode
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
if setdarkmode:
darkPalette = QPalette()
darkColor = QColor(56, 56, 56)
disabledColor = QColor(127, 127, 127)
darkPalette.setColor(QPalette.ColorRole.Window, darkColor)
darkPalette.setColor(QPalette.ColorRole.WindowText, QColorConstants.White)
darkPalette.setColor(QPalette.ColorRole.Base, QColor(45, 45, 45))
darkPalette.setColor(QPalette.ColorRole.AlternateBase, darkColor)
darkPalette.setColor(QPalette.ColorRole.Text, QColorConstants.White)
darkPalette.setColor(QPalette.ColorRole.Button, darkColor)
darkPalette.setColor(QPalette.ColorRole.ButtonText, QColorConstants.White)
darkPalette.setColor(QPalette.ColorRole.BrightText, QColorConstants.Red)
darkPalette.setColor(QPalette.ColorRole.Link, QColor(42, 130, 218))
darkPalette.setColor(QPalette.ColorRole.Highlight, QColor(42, 130, 218))
darkPalette.setColor(
QPalette.ColorRole.HighlightedText, QColorConstants.Black
)
darkPalette.setColor(
QPalette.ColorGroup.Disabled,
QPalette.ColorRole.ButtonText,
disabledColor,
)
darkPalette.setColor(
QPalette.ColorGroup.Disabled,
QPalette.ColorRole.HighlightedText,
disabledColor,
)
darkPalette.setColor(
QPalette.ColorGroup.Disabled,
QPalette.ColorRole.Text,
disabledColor,
)
self.current_palette = darkPalette
self.setPalette(darkPalette)
self.text_color = QColorConstants.White
self.menuFile.setPalette(darkPalette)
self.menuHelp.setPalette(darkPalette)
self.menuOther.setPalette(darkPalette)
self.menuView.setPalette(darkPalette)
self.menuWindow.setPalette(darkPalette)
self.callsign.setPalette(darkPalette)
self.sent.setPalette(darkPalette)
self.receive.setPalette(darkPalette)
self.other_1.setPalette(darkPalette)
self.other_2.setPalette(darkPalette)
self.cw_entry.setPalette(darkPalette)
else:
palette = self.style().standardPalette()
self.current_palette = palette
self.setPalette(palette)
self.menuFile.setPalette(palette)
self.menuHelp.setPalette(palette)
self.menuOther.setPalette(palette)
self.menuView.setPalette(palette)
self.menuWindow.setPalette(palette)
self.callsign.setPalette(palette)
self.sent.setPalette(palette)
self.receive.setPalette(palette)
self.other_1.setPalette(palette)
self.other_2.setPalette(palette)
self.cw_entry.setPalette(palette)
self.text_color = QColorConstants.Black
def set_radio_icon(self, state: int) -> None:
"""
Change CAT icon state
Parameters
----------
state : int
The state of the CAT icon. 0 = grey, 1 = red, 2 = green
Returns
-------
None
"""
displaystate = [self.radio_grey, self.radio_red, self.radio_green]
try:
self.radio_icon.setPixmap(displaystate[state])
except (IndexError, TypeError) as err:
logger.debug(err)
def toggle_cw_entry(self) -> None:
"""
Toggle the CW entry field on and off.
Parameters
----------
None
Returns
-------
None
"""
self.cw_entry_visible = not self.cw_entry_visible
if self.cw_entry_visible:
self.last_focus = app.focusWidget()
self.cw_entry.clear()
self.cw_entry.show()
self.cw_entry.setFocus()
return
self.cw_entry.hide()
self.cw_entry.clearFocus()
if self.last_focus:
self.last_focus.setFocus()
def handle_text_change(self) -> None:
"""
....
Parameters
----------
None
Returns
-------
None
"""
newtext = self.cw_entry.text()
if len(newtext) < len(self.oldtext):
# self.send_backspace()
self.oldtext = newtext
return
if self.pref.get("cwtype") == 3 and self.rig_control is not None:
self.rig_control.sendcw(newtext[len(self.oldtext) :])
elif self.cw is not None:
self.cw.sendcw(newtext[len(self.oldtext) :])
self.oldtext = newtext
def change_to_band_and_mode(self, band: int, mode: str) -> None:
"""
Gets a sane frequency for the chosen band and mode.
Then changes to that,
Parameters
----------
band : int
mode : str
Returns
-------
Nothing
"""
if mode in ["CW", "SSB", "RTTY"]:
freq = fakefreq(str(band), mode)
self.change_freq(freq)
vfo = float(freq)
vfo = int(vfo * 1000)
if mode == "CW":
mode = self.rig_control.last_cw_mode
if mode == "RTTY":
mode = self.rig_control.last_data_mode
self.change_mode(mode, intended_freq=vfo)
def quit_app(self) -> None:
"""
Send multicast quit message, then quit the program.
Parameters
----------
None
Returns
-------
None
"""
self.write_preference()
cmd = {}
cmd["cmd"] = "HALT"
if self.lookup_service:
self.lookup_service.msg_from_main(cmd)
app.quit()
def show_message_box(self, message: str, blocking: bool = True) -> None:
"""
Displays a dialog box with a message.
Paramters
---------
message : str
Returns
-------
None
"""
message_box = QtWidgets.QMessageBox()
if self.current_palette:
message_box.setPalette(self.current_palette)
message_box.setIcon(QtWidgets.QMessageBox.Icon.Information)
message_box.setText(message)
message_box.setWindowTitle("Information")
message_box.setStandardButtons(QtWidgets.QMessageBox.StandardButton.Ok)
if blocking is False:
message_box.setWindowModality(Qt.WindowModality.WindowModal)
_ = message_box.exec()
def show_about_dialog(self) -> None:
"""
Show the About dialog when the menu item is clicked.
Parameters
----------
Takes no parameters.
Returns
-------
None
"""
self.about_dialog = About(fsutils.APP_DATA_PATH)
if self.current_palette:
self.about_dialog.setPalette(self.current_palette)
self.about_dialog.donors.setSource(
QtCore.QUrl.fromLocalFile(f"{fsutils.APP_DATA_PATH / 'donors.html'}")
)
self.about_dialog.open()
def show_help_dialog(self):
"""
Show the Help dialog when the menu item is clicked.
Parameters
----------
Takes no parameters.
Returns
-------
None
"""
self.about_dialog = About(fsutils.APP_DATA_PATH)
if self.current_palette:
self.about_dialog.setPalette(self.current_palette)
self.about_dialog.setWindowTitle("Help")
self.about_dialog.setGeometry(0, 0, 800, 600)
self.about_dialog.donors.setSource(
QtCore.QUrl.fromLocalFile(str(fsutils.APP_DATA_PATH / "not1mm.html"))
)
self.about_dialog.open()
def update_masterscp(self) -> None:
"""
Tries to update the MASTER.SCP file when the menu item is clicked.
Displays a dialog advising if it was updated.
Parameters
----------
Takes no parameters.
Returns
-------
None
"""
if self.mscp.update_masterscp():
self.show_message_box("MASTER.SCP file updated.", blocking=False)
return
self.show_message_box("MASTER.SCP could not be updated.", blocking=False)
def edit_configuration_settings(self) -> None:
"""
Configuration Settings was clicked
Parameters
----------
None
Returns
-------
None
"""
self.configuration_dialog = Settings(fsutils.APP_DATA_PATH, self.pref)
if self.current_palette:
self.configuration_dialog.setPalette(self.current_palette)
self.configuration_dialog.usehamdb_radioButton.hide()
self.configuration_dialog.show()
self.configuration_dialog.accepted.connect(self.edit_configuration_return)
def edit_configuration_return(self) -> None:
"""
Returns here when configuration dialog closed with okay.
Parameters
----------
None
Returns
-------
None
"""
self.configuration_dialog.save_changes()
self.write_preference()
# logger.debug("%s", f"{self.pref}")
self.readpreferences()
def new_database(self) -> None:
"""
Create new database file.
Parameters
----------
None
Returns
-------
None
"""
filename = self.filepicker("new")
if filename:
if filename[-3:] != ".db":
filename += ".db"
self.pref["current_database"] = os.path.basename(filename)
self.write_preference()
self.dbname = fsutils.USER_DATA_PATH / self.pref.get(
"current_database", "ham.db"
)
self.database = DataBase(self.dbname, fsutils.APP_DATA_PATH)
self.contact = self.database.empty_contact.copy()
self.previous_contact = self.contact
self.station = self.database.fetch_station()
if self.station is None:
self.station = {}
if self.rotator_window is not None:
self.rotator_window.set_mygrid(self.station.get("GridSquare", ""))
self.current_op = self.station.get("Call", "")
self.voice_process.current_op = self.current_op
self.make_op_dir()
cmd = {}
cmd["cmd"] = "NEWDB"
if self.log_window:
self.log_window.msg_from_main(cmd)
if self.rate_window:
self.rate_window.msg_from_main(cmd)
if self.statistics_window:
self.statistics_window.msg_from_main(cmd)
if self.dxcc_window:
self.dxcc_window.msg_from_main(cmd)
if self.zone_window:
self.zone_window.msg_from_main(cmd)
if self.chat_window:
self.chat_window.mycall = self.current_op
self.clearinputs()
self.edit_station_settings()
def open_database(self) -> None:
"""
Open existing database file.
Parameters
----------
None
Returns
-------
None
"""
filename = self.filepicker("open")
if filename:
self.pref["current_database"] = os.path.basename(filename)
self.write_preference()
self.dbname = fsutils.USER_DATA_PATH / self.pref.get(
"current_database", "ham.db"
)
self.database = DataBase(self.dbname, fsutils.MODULE_PATH)
self.contact = self.database.empty_contact.copy()
self.previous_contact = self.contact
self.station = self.database.fetch_station()
if self.station is None:
self.station = {}
if self.rotator_window is not None:
self.rotator_window.set_mygrid(self.station.get("GridSquare", ""))
if self.station.get("Call", "") == "":
self.edit_station_settings()
self.current_op = self.station.get("Call", "")
self.voice_process.current_op = self.current_op
self.make_op_dir()
cmd = {}
cmd["cmd"] = "NEWDB"
if self.log_window:
self.log_window.msg_from_main(cmd)
if self.rate_window:
self.rate_window.msg_from_main(cmd)
if self.statistics_window:
self.statistics_window.msg_from_main(cmd)
if self.dxcc_window:
self.dxcc_window.msg_from_main(cmd)
if self.zone_window:
self.zone_window.msg_from_main(cmd)
if self.chat_window:
self.chat_window.mycall = self.current_op
self.clearinputs()
self.open_contest()
def new_contest(self) -> None:
"""Create new contest in existing database."""
def open_contest(self) -> None:
"""
Switch to a different existing contest in existing database.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("Open Contest selected")
contests = self.database.fetch_all_contests()
logger.debug("%s", f"{contests}")
if contests:
self.contest_dialog = SelectContest(fsutils.APP_DATA_PATH)
if self.current_palette:
self.contest_dialog.setPalette(self.current_palette)
self.contest_dialog.contest_list.setRowCount(0)
self.contest_dialog.contest_list.setColumnCount(4)
self.contest_dialog.contest_list.verticalHeader().setVisible(False)
self.contest_dialog.contest_list.setColumnWidth(1, 200)
self.contest_dialog.contest_list.setColumnWidth(2, 200)
self.contest_dialog.contest_list.setHorizontalHeaderItem(
0, QtWidgets.QTableWidgetItem("Contest Nr")
)
self.contest_dialog.contest_list.setHorizontalHeaderItem(
1, QtWidgets.QTableWidgetItem("Contest Name")
)
self.contest_dialog.contest_list.setHorizontalHeaderItem(
2, QtWidgets.QTableWidgetItem("Contest Start")
)
self.contest_dialog.contest_list.setHorizontalHeaderItem(
3, QtWidgets.QTableWidgetItem("Not UIsed")
)
self.contest_dialog.contest_list.setColumnHidden(0, True)
self.contest_dialog.contest_list.setColumnHidden(3, True)
self.contest_dialog.accepted.connect(self.open_contest_return)
for contest in contests:
number_of_rows = self.contest_dialog.contest_list.rowCount()
self.contest_dialog.contest_list.insertRow(number_of_rows)
contest_id = str(contest.get("ContestID", 1))
contest_name = contest.get("ContestName", 1)
start_date = contest.get("StartDate", 1)
self.contest_dialog.contest_list.setItem(
number_of_rows, 0, QtWidgets.QTableWidgetItem(contest_id)
)
self.contest_dialog.contest_list.setItem(
number_of_rows, 1, QtWidgets.QTableWidgetItem(contest_name)
)
self.contest_dialog.contest_list.setItem(
number_of_rows, 2, QtWidgets.QTableWidgetItem(start_date)
)
self.contest_dialog.show()
def open_contest_return(self) -> None:
"""
Called by open_contest when contest selected.
Parameters
----------
None
Returns
-------
None
"""
selected_row = self.contest_dialog.contest_list.currentRow()
contest = self.contest_dialog.contest_list.item(selected_row, 0).text()
self.pref["contest"] = contest
self.write_preference()
logger.debug("Selected contest: %s", f"{contest}")
self.load_contest()
self.worked_list = self.database.get_calls_and_bands()
self.send_worked_list()
def refill_dropdown(self, target, source) -> None:
"""
Refill QCombobox widget with value.
Parameters
----------
target : QComboBox
The target widget to be refilled
source : str
The value to be used to fill the target widget
Returns
-------
None
"""
index = target.findText(source)
target.setCurrentIndex(index)
def edit_contest(self) -> None:
"""
Edit the current contest settings.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("Edit contest Dialog")
if self.contest is None:
self.show_message_box("You have no contest defined.")
return
if self.contest_settings is None:
return
self.contest_dialog = NewContest(fsutils.APP_DATA_PATH)
if self.current_palette:
self.contest_dialog.setPalette(self.current_palette)
self.contest_dialog.exchange.setPalette(self.current_palette)
self.contest_dialog.operators.setPalette(self.current_palette)
self.contest_dialog.contest.setPalette(self.current_palette)
self.contest_dialog.setWindowTitle("Edit Contest")
self.contest_dialog.title.setText("")
self.contest_dialog.accepted.connect(self.save_edited_contest)
value = self.contest_settings.get("ContestName").upper().replace("_", " ")
if value == "GENERAL LOGGING":
value = "General Logging"
self.refill_dropdown(self.contest_dialog.contest, value)
value = self.contest_settings.get("OperatorCategory")
self.refill_dropdown(self.contest_dialog.operator_class, value)
value = self.contest_settings.get("BandCategory")
self.refill_dropdown(self.contest_dialog.band, value)
value = self.contest_settings.get("PowerCategory")
self.refill_dropdown(self.contest_dialog.power, value)
value = self.contest_settings.get("ModeCategory")
self.refill_dropdown(self.contest_dialog.mode, value)
value = self.contest_settings.get("OverlayCategory")
self.refill_dropdown(self.contest_dialog.overlay, value)
self.contest_dialog.operators.setText(self.contest_settings.get("Operators"))
self.contest_dialog.soapbox.setPlainText(self.contest_settings.get("Soapbox"))
self.contest_dialog.exchange.setText(self.contest_settings.get("SentExchange"))
value = self.contest_settings.get("StationCategory")
self.refill_dropdown(self.contest_dialog.station, value)
value = self.contest_settings.get("AssistedCategory")
self.refill_dropdown(self.contest_dialog.assisted, value)
value = self.contest_settings.get("TransmitterCategory")
self.refill_dropdown(self.contest_dialog.transmitter, value)
value = self.contest_settings.get("StartDate")
the_date, the_time = value.split()
self.contest_dialog.dateTimeEdit.setDate(
QtCore.QDate.fromString(the_date, "yyyy-MM-dd")
)
self.contest_dialog.dateTimeEdit.setCalendarPopup(True)
self.contest_dialog.dateTimeEdit.setTime(
QtCore.QTime.fromString(the_time, "hh:mm:ss")
)
self.contest_dialog.open()
def save_edited_contest(self) -> None:
"""
Save the edited contest.
Called by edit_contest().
Parameters
----------
None
Returns
-------
None
"""
contest = {}
contest["ContestName"] = (
self.contest_dialog.contest.currentText().lower().replace(" ", "_")
)
contest["StartDate"] = self.contest_dialog.dateTimeEdit.dateTime().toString(
"yyyy-MM-dd hh:mm:ss"
)
contest["OperatorCategory"] = self.contest_dialog.operator_class.currentText()
contest["BandCategory"] = self.contest_dialog.band.currentText()
contest["PowerCategory"] = self.contest_dialog.power.currentText()
contest["ModeCategory"] = self.contest_dialog.mode.currentText()
contest["OverlayCategory"] = self.contest_dialog.overlay.currentText()
contest["Operators"] = self.contest_dialog.operators.text()
contest["Soapbox"] = self.contest_dialog.soapbox.toPlainText()
contest["SentExchange"] = self.contest_dialog.exchange.text()
contest["ContestNR"] = self.pref.get("contest", 1)
contest["StationCategory"] = self.contest_dialog.station.currentText()
contest["AssistedCategory"] = self.contest_dialog.assisted.currentText()
contest["TransmitterCategory"] = self.contest_dialog.transmitter.currentText()
logger.debug("%s", f"{contest}")
self.database.update_contest(contest)
self.write_preference()
self.load_contest()
def load_contest(self) -> None:
"""
Loads the contest stored in the preference file.
If no contest is defined, a new contest is created.
Parameters
----------
None
Returns
-------
None
"""
if self.pref.get("contest"):
self.contest_settings = self.database.fetch_contest_by_id(
self.pref.get("contest")
)
if self.contest_settings:
try:
self.database.current_contest = self.pref.get("contest")
if self.contest_settings.get("ContestName"):
"""Reset these in case a contest disabled them"""
self.other_1.setStyleSheet("text-transform: uppercase;")
self.other_2.setStyleSheet("text-transform: uppercase;")
"""Reset this too, in case user set it"""
self.RoverLocation = ""
"""Inform check window in case this is a change of contest"""
self.check_window.database.current_contest = self.pref.get(
"contest"
)
self.contest = doimp(self.contest_settings.get("ContestName"))
logger.debug("Loaded Contest Name = %s", self.contest.name)
self.set_window_title()
self.contest.init_contest(self)
self.hide_band_mode(
self.contest_settings.get("ModeCategory", "")
)
logger.debug("%s", f"{self.contest_settings}")
if self.contest_settings.get("ModeCategory", "") == "CW":
self.setmode("CW")
self.radio_state["mode"] = "CW"
if self.rig_control:
if self.rig_control.online:
self.rig_control.set_mode("CW")
band = getband(str(self.radio_state.get("vfoa", "0.0")))
self.set_band_indicator(band)
self.set_window_title()
if self.contest_settings.get("ModeCategory", "") == "RTTY":
self.setmode("RTTY")
self.radio_state["mode"] = "RTTY"
if self.rig_control:
if self.rig_control.online:
self.rig_control.set_mode("RTTY")
band = getband(str(self.radio_state.get("vfoa", "0.0")))
self.set_band_indicator(band)
self.set_window_title()
if self.contest_settings.get("ModeCategory", "") == "SSB":
self.setmode("SSB")
if int(self.radio_state.get("vfoa", 0)) > 10000000:
self.radio_state["mode"] = "USB"
else:
self.radio_state["mode"] = "LSB"
band = getband(str(self.radio_state.get("vfoa", "0.0")))
self.set_band_indicator(band)
self.set_window_title()
if self.rig_control:
self.rig_control.set_mode(self.radio_state.get("mode"))
self.update_rtc_xml()
except ModuleNotFoundError:
self.pref["contest"] = 1
self.show_message_box("Contest plugin not found")
if hasattr(self.contest, "mode"):
logger.debug("%s", f" **** {self.contest}")
if self.contest.mode in ["CW", "BOTH"]:
self.cw_speed.show()
else:
self.cw_speed.hide()
if hasattr(self.contest, "ft8_handler"):
self.contest.set_self(self)
self.ft8.set_callback(self.contest.ft8_handler)
else:
self.ft8.set_callback(None)
self.clearinputs()
cmd = {}
cmd["cmd"] = "NEWDB"
if self.log_window:
self.log_window.msg_from_main(cmd)
if self.rate_window:
self.rate_window.msg_from_main(cmd)
if self.statistics_window:
self.statistics_window.msg_from_main(cmd)
if self.dxcc_window:
self.dxcc_window.msg_from_main(cmd)
if self.zone_window:
self.zone_window.msg_from_main(cmd)
# server
if (
self.pref.get("useserver", False) is True
and self.pref.get("im_the_master", False) is True
):
cmd = self.contest_settings.copy()
cmd["cmd"] = "NEWDB"
stale = datetime.datetime.now() + datetime.timedelta(seconds=30)
cmd["expire"] = stale.isoformat()
cmd["NetBiosName"] = socket.gethostname()
cmd["Operator"] = self.current_op
cmd["ID"] = uuid.uuid4().hex
cmd["Station"] = self.station
# self.server_commands.append(cmd)
# bytesToSend = bytes(dumps(self.contact), encoding="ascii")
try:
self.server_channel.send_as_json(cmd)
# server_udp.sendto(bytesToSend, (multicast_group, int(multicast_port)))
except OSError as err:
logging.warning("%s", err)
if hasattr(self.contest, "columns"):
cmd = {}
cmd["cmd"] = "SHOWCOLUMNS"
cmd["COLUMNS"] = self.contest.columns
if self.log_window:
self.log_window.msg_from_main(cmd)
self.read_macros()
def check_for_new_cty(self) -> None:
"""
Checks for a new cty.dat file.
The following steps are performed:
- Check if the file exists
- Check if the file is newer than the one in the data folder
- If the file is newer, load it and show a message box
Parameters
----------
None
Returns
-------
None
"""
try:
cty = notctyparser.BigCty(fsutils.APP_DATA_PATH / "cty.json")
update_available = cty.check_update()
except (AttributeError, ValueError, locale.Error) as the_error:
logger.debug("cty parser returned an error: %s", the_error)
return
logger.debug("Newer cty file available %s", str(update_available))
if update_available:
try:
updated = cty.update()
except ResourceWarning as the_error:
logger.debug("cty parser returned an error: %s", the_error)
return
if updated:
cty.dump(fsutils.APP_DATA_PATH / "cty.json")
self.show_message_box("cty file updated.", blocking=False)
try:
with open(
fsutils.APP_DATA_PATH / "cty.json", "rt", encoding="utf-8"
) as ctyfile:
self.ctyfile = loads(ctyfile.read())
except (IOError, JSONDecodeError, TypeError) as err:
logging.critical(
f"There was an error {err} parsing the BigCity file."
)
else:
self.show_message_box(
"An Error occurred updating file.", blocking=False
)
else:
self.show_message_box("CTY file is up to date.", blocking=False)
def hide_band_mode(self, the_mode: str) -> None:
"""
Hide the unused band and mode frames.
Show the used band and mode frames.
Parameters
----------
the_mode : str
The mode to show.
Returns
-------
None
"""
logger.debug("%s", f"{the_mode}")
self.Band_Mode_Frame_CW.hide()
self.Band_Mode_Frame_SSB.hide()
self.Band_Mode_Frame_RTTY.hide()
modes = {
"CW": (self.Band_Mode_Frame_CW,),
"SSB": (self.Band_Mode_Frame_SSB,),
"RTTY": (self.Band_Mode_Frame_RTTY,),
"PSK": (self.Band_Mode_Frame_RTTY,),
"SSB+CW": (self.Band_Mode_Frame_CW, self.Band_Mode_Frame_SSB),
"BOTH": (self.Band_Mode_Frame_CW, self.Band_Mode_Frame_SSB),
"DIGITAL": (self.Band_Mode_Frame_RTTY,),
"SSB+CW+DIGITAL": (
self.Band_Mode_Frame_RTTY,
self.Band_Mode_Frame_CW,
self.Band_Mode_Frame_SSB,
),
"FM": (self.Band_Mode_Frame_SSB,),
}
frames = modes.get(the_mode)
if frames:
for frame in frames:
frame.show()
def show_key_help(self) -> None:
"""
Show help box for hotkeys.
Provides a list of hotkeys and what they do.
Parameters
----------
None
Returns
-------
None
"""
self.show_message_box(
"[ESC]\tStops CW sending and antenna rotation.\n"
"[PgUp]\tIncreases the cw sending speed.\n"
"[PgDown]\tDecreases the cw sending speed.\n"
"[Arrow-Up] Jump to the next spot above the current VFO cursor\n"
"\tin the bandmap window (CAT Required).\n"
"[Arrow-Down] Jump to the next spot below the current\n"
"\tVFO cursor in the bandmap window (CAT Required).\n"
"[TAB]\tMove cursor to the right one field.\n"
"[Shift-Tab]\tMove cursor left One field.\n"
"[SPACE]\tWhen in the callsign field, will move the input to the\n"
"\tfirst field needed for the exchange.\n"
"[Enter]\tSubmits the fields to the log. Unless ESM is enabled.\n"
"[F1-F12]\tSend (CW or Voice) macros.\n"
"[CTRL-G]\tTune to a spot matching partial text in the callsign\n"
"\tentry field (CAT Required).\n"
"[CTRL-M]\tMark Callsign to the bandmap window to work later."
"[CTRL-S]\tSpot Callsign to the cluster.\n"
"[CTRL-SHIFT-K] Open CW text input field.\n"
"[CTRL-=]\tLog the contact without sending the ESM macros.\n"
"[CTRL-W]\tClears the input fields of any text.\n"
"[CTRL-R]\tToggle the Run state.\n"
"[CTRL-Q]\tJump to last CQ frequency.\n",
blocking=False,
)
def filepicker(self, action: str) -> str:
"""
Get a filename
Parameters:
----------
action: 'new' or 'open'
Returns:
-------
str: filename
"""
options = (
QFileDialog.Option.DontUseNativeDialog
| QFileDialog.Option.DontConfirmOverwrite
)
if action == "new":
file, _ = QFileDialog.getSaveFileName(
self,
"Choose a Database",
str(fsutils.USER_DATA_PATH),
"Database (*.db)",
options=options,
)
if action == "open":
file, _ = QFileDialog.getOpenFileName(
self,
"Choose a Database",
str(fsutils.USER_DATA_PATH),
"Database (*.db)",
options=options,
)
if action == "other":
file, _ = QFileDialog.getOpenFileName(
self,
"Choose a File",
"~/",
"Any (*.*)",
options=options,
)
return file
def recalculate_mults(self) -> None:
"""Recalculate Multipliers"""
self.contest.recalculate_mults(self)
self.clearinputs()
def mark_all_dirty(self) -> None:
"""Mark all contacts dirty"""
self.database.make_all_dirty()
self.resolve_dirty_records()
def launch_log_window(self) -> None:
"""Launch or close the log window"""
self.pref["logwindow"] = self.actionLog_Window.isChecked()
self.write_preference()
if self.actionLog_Window.isChecked():
self.log_window.show()
else:
self.log_window.hide()
def launch_bandmap_window(self) -> None:
"""Launch or close the bandmap window"""
self.pref["bandmapwindow"] = self.actionBandmap.isChecked()
self.write_preference()
if self.actionBandmap.isChecked():
self.bandmap_window.show()
self.bandmap_window.setActive(True)
else:
self.bandmap_window.hide()
self.bandmap_window.setActive(False)
def launch_check_window(self) -> None:
"""Launch or close the check window"""
self.pref["checkwindow"] = self.actionCheck_Window.isChecked()
self.write_preference()
if self.actionCheck_Window.isChecked():
self.check_window.show()
self.check_window.setActive(True)
else:
self.check_window.hide()
self.check_window.setActive(False)
def launch_rate_window(self) -> None:
"""Launch or close the rate window"""
self.pref["ratewindow"] = self.actionRate_Window.isChecked()
self.write_preference()
if self.actionRate_Window.isChecked():
self.rate_window.show()
self.rate_window.setActive(True)
else:
self.rate_window.hide()
self.rate_window.setActive(False)
def launch_stats_window(self) -> None:
"""Launch or close the stats window"""
self.pref["statisticswindow"] = self.actionStatistics.isChecked()
self.write_preference()
if self.actionStatistics.isChecked():
self.statistics_window.show()
self.statistics_window.setActive(True)
self.statistics_window.get_run_and_total_qs()
else:
self.statistics_window.hide()
self.statistics_window.setActive(False)
def launch_dxcc_window(self) -> None:
"""Launch or close the dxcc window"""
self.pref["dxccwindow"] = self.actionDXCC.isChecked()
self.write_preference()
if self.actionDXCC.isChecked():
self.dxcc_window.show()
self.dxcc_window.setActive(True)
self.dxcc_window.get_log()
else:
self.dxcc_window.hide()
self.dxcc_window.setActive(False)
def launch_zone_window(self) -> None:
"""Launch or close the zone window"""
self.pref["zonewindow"] = self.actionZone.isChecked()
self.write_preference()
if self.actionZone.isChecked():
self.zone_window.show()
self.zone_window.setActive(True)
self.zone_window.get_log()
else:
self.zone_window.hide()
self.zone_window.setActive(False)
def launch_rotator_window(self) -> None:
"""Launch or close the rotator window"""
self.pref["rotatorwindow"] = self.actionRotator.isChecked()
self.write_preference()
if self.actionRotator.isChecked():
self.rotator_window.show()
self.rotator_window.setActive(True)
else:
self.rotator_window.hide()
self.rotator_window.setActive(False)
def launch_vfo(self) -> None:
"""Launch or close the VFO window"""
self.pref["vfowindow"] = self.actionVFO.isChecked()
self.write_preference()
if self.actionVFO.isChecked():
self.vfo_window.show()
else:
self.vfo_window.hide()
def launch_chat_window(self) -> None:
"""Launch or close the chat window"""
self.pref["chatwindow"] = self.actionGroup_Chat.isChecked()
self.write_preference()
if self.actionGroup_Chat.isChecked():
self.chat_window.show()
self.chat_window.setActive(True)
else:
self.chat_window.hide()
self.chat_window.setActive(False)
def clear_band_indicators(self) -> None:
"""
Clear the indicators.
Parameters:
----------
None
Returns:
-------
None
"""
for _, indicators in self.all_mode_indicators.items():
for _, indicator in indicators.items():
indicator.setFrameShape(QtWidgets.QFrame.Shape.NoFrame)
if self.text_color == QColorConstants.Black:
indicator.setStyleSheet("color: black;")
else:
indicator.setStyleSheet("color: white;")
def set_band_indicator(self, band: str) -> None:
"""
Set the band indicator
Parameters:
----------
band: str
band to set indicator for
Returns:
-------
None
"""
if band and self.current_mode:
self.clear_band_indicators()
indicator = self.all_mode_indicators[self.current_mode].get(band, None)
if indicator:
indicator.setFrameShape(QtWidgets.QFrame.Shape.Box)
indicator.setStyleSheet("color: rgb(127,127,0);")
def closeEvent(self, _event: QCloseEvent) -> None:
"""
Write window size and position to config file.
Parameters:
----------
_event: QCloseEvent
Returns:
-------
None
"""
self.settings.setValue("geometry", self.saveGeometry())
self.settings.setValue("windowState", self.saveState())
self.settings.sync()
try: # Shutdown the radio thread.
if self.radio_thread.isRunning():
self.rig_control.time_to_quit = True
self.radio_thread.quit()
self.radio_thread.wait(1000)
except (RuntimeError, AttributeError):
...
cmd = {}
cmd["cmd"] = "HALT"
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
if self.log_window:
self.log_window.msg_from_main(cmd)
if self.lookup_service:
self.lookup_service.msg_from_main(cmd)
self.write_preference()
def cty_lookup(self, callsign: str) -> dict:
"""Lookup callsign in cty.dat file.
Parameters
----------
callsign : str
callsign to lookup
Returns
-------
return : dict
{'entity': 'European Russia', 'cq': 16, 'itu': 29, 'continent': 'EU', 'lat': 53.65, 'long': -41.37, 'tz': 4.0, 'len': 2, 'primary_pfx': 'UA', 'exact_match': False}
"""
callsign = callsign.upper()
for count in reversed(range(len(callsign))):
searchitem = callsign[: count + 1]
result = {
key: val for key, val in self.ctyfile.items() if key == searchitem
}
if not result:
continue
if result.get(searchitem).get("exact_match"):
if searchitem == callsign:
return result
continue
return result
def cwspeed_spinbox_changed(self) -> None:
"""
Triggered when value of CW speed in the spinbox changes.
Parameters:
----------
None
Returns:
-------
None
"""
self.pref["cw_speed"] = self.cw_speed.value()
if self.cw is None:
return
self.cw.speed = self.cw_speed.value()
if self.cw.servertype == 1:
self.cw.sendcw(f"\x1b2{self.cw.speed}")
if self.cw.servertype == 2:
self.cw.set_winkeyer_speed(self.cw.speed)
if self.rig_control and self.rig_control.cat:
if self.pref.get("cwtype") == 3:
if self.rig_control.interface == "flrig":
self.rig_control.cat.set_flrig_cw_speed(self.cw.speed)
elif self.rig_control.interface == "rigctld":
self.rig_control.cat.set_rigctl_cw_speed(self.cw.speed)
def stop_cw(self) -> None:
""""""
self.auto_cq = False
self.leftdot.hide()
self.cwprogressBar.hide()
if self.cw is not None:
if self.cw.servertype == 1:
self.cw.sendcw("\x1b4")
return
if self.cw.servertype == 2:
self.cw.winkeyer_stop()
return
if self.rig_control and self.rig_control.cat:
if self.rig_control.online:
if self.pref.get("cwtype") == 3:
if self.rig_control.interface == "flrig":
self.rig_control.cat.set_flrig_cw_send(False)
self.rig_control.cat.set_flrig_cw_send(True)
if self.rig_control.interface == "rigctld":
self.rig_control.cat.stopcwrigctl()
def stop_all(self) -> None:
"""Stop CW and rotator."""
self.stop_cw()
if self.rotator_window is not None:
self.rotator_window.stop()
def mark_cq(self) -> None:
"""
Mark CQ frequency in bandmap. Remember the last frequency so we don't re-add a new spot every few seconds.
"""
freq = self.radio_state.get("vfoa")
if freq and freq != self.cq_freq and self.bandmap_window:
cmd = {}
cmd["cmd"] = "MARKDX"
cmd["dx"] = "CQ"
cmd["freq"] = float(int(freq) / 1000)
cmd["comment"] = f"CQ {self.current_mode} MARKED"
self.bandmap_window.msg_from_main(cmd)
self.cq_freq = freq
def mark_spot(self, comment="") -> None:
""""""
freq = self.radio_state.get("vfoa")
dx = self.callsign.text()
if freq and dx:
cmd = {}
cmd["cmd"] = "MARKDX"
cmd["dx"] = dx
cmd["freq"] = float(int(freq) / 1000)
cmd["comment"] = comment
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
def spot_dx(self) -> None:
"""If a bandmap_window exists, send it a SPOTDX command to forward info to the cluster."""
if self.bandmap_window:
freq = self.radio_state.get("vfoa")
dx = self.callsign.text()
if freq and dx:
cmd = {"cmd": "SPOTDX", "dx": dx, "freq": float(int(freq) / 1000)}
elif self.previous_contact["Call"] and self.previous_contact["Freq"]:
cmd = {
"cmd": "SPOTDX",
"dx": self.previous_contact["Call"],
"freq": self.previous_contact["Freq"],
}
else:
cmd = None
if cmd:
self.bandmap_window.msg_from_main(cmd)
def get_sn(self) -> None:
"""Generate a serial number."""
# {
# "cmd": "GET_SN",
# "Operator": "K6GTE",
# "NetBiosName": "fredo",
# }
if (
self.pref.get("useserver", False) is True
and self.contest_settings.get("OperatorCategory", "") in ("MULTI-OP")
and self.contest_settings.get("TransmitterCategory", "")
not in ("ONE", "SWL")
):
if self.current_sn is None:
self.current_sn = "REQUESTED"
cmd = {}
cmd["cmd"] = "GET_SN"
cmd["Operator"] = self.current_op
cmd["NetBiosName"] = socket.gethostname()
try:
self.server_channel.send_as_json(cmd)
except OSError as err:
logging.warning("%s", err)
else:
result = self.database.get_serial()
self.current_sn = str(result.get("serial_nr", "1"))
if self.current_sn == "None":
self.current_sn = "1"
def keyPressEvent(self, event: QKeyEvent) -> None: # pylint: disable=invalid-name
"""
This overrides Qt key event.
Parameters:
----------
event: QKeyEvent
Qt key event
Returns:
-------
None
Control
QWRTYIOPSFGHJLBNM,./;'[]//-
shift control
ABCDEFGHIJKLMNOPQRSTUVWXY
"""
modifier = event.modifiers()
if (
event.key() in [Qt.Key.Key_Equal, Qt.Key.Key_L]
and modifier == Qt.KeyboardModifier.ControlModifier
):
self.save_contact()
return
if event.key() == Qt.Key.Key_K:
self.toggle_cw_entry()
return
if (
event.key() == Qt.Key.Key_S
and modifier == Qt.KeyboardModifier.ControlModifier
):
freq = self.radio_state.get("vfoa")
dx = self.callsign.text()
if freq and dx:
cmd = {}
cmd["cmd"] = "SPOTDX"
cmd["dx"] = dx
cmd["freq"] = float(int(freq) / 1000)
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
return
if (
event.key() == Qt.Key.Key_M
and modifier == Qt.KeyboardModifier.ControlModifier
):
self.mark_spot(comment=f"{self.current_mode} MARKED")
return
if (
event.key() == Qt.Key.Key_G
and modifier == Qt.KeyboardModifier.ControlModifier
):
dx = self.callsign.text()
if dx:
cmd = {}
cmd["cmd"] = "FINDDX"
cmd["dx"] = dx
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
return
if (
event.key() == Qt.Key.Key_Q
and modifier == Qt.KeyboardModifier.ControlModifier
): # pylint: disable=no-member
if self.cq_freq:
self.radio_state["vfoa"] = self.cq_freq
if self.rig_control:
self.rig_control.set_vfo(self.cq_freq)
self.set_running(True)
self.clearinputs()
return
if (
event.key() == Qt.Key.Key_R
and modifier == Qt.KeyboardModifier.ControlModifier
): # pylint: disable=no-member
self.toggle_run_sp()
return
if (
event.key() == Qt.Key.Key_T
and modifier == Qt.KeyboardModifier.ControlModifier
): # pylint: disable=no-member
if hasattr(self.contest, "add_test_data"):
self.contest.add_test_data(self)
return
if (
event.key() == Qt.Key.Key_W
and modifier == Qt.KeyboardModifier.ControlModifier
): # pylint: disable=no-member
self.clearinputs()
return
if (
event.key() == Qt.Key.Key_Escape
and modifier != Qt.KeyboardModifier.ControlModifier
):
self.stop_all()
if event.key() == Qt.Key.Key_Up:
cmd = {}
cmd["cmd"] = "PREVSPOT"
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
return
if event.key() == Qt.Key.Key_Down:
cmd = {}
cmd["cmd"] = "NEXTSPOT"
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
return
if (
event.key() == Qt.Key.Key_PageUp
and modifier != Qt.KeyboardModifier.ControlModifier
):
if self.cw is not None:
self.cw.speed += self.pref.get("cwstepping", 1)
self.cw_speed.setValue(self.cw.speed)
if self.cw.servertype == 1:
self.cw.sendcw(f"\x1b2{self.cw.speed}")
if self.cw.servertype == 2:
self.cw.set_winkeyer_speed(self.cw_speed.value())
return
if (
event.key() == Qt.Key.Key_PageDown
and modifier != Qt.KeyboardModifier.ControlModifier
):
if self.cw is not None:
self.cw.speed -= self.pref.get("cwstepping", 1)
self.cw_speed.setValue(self.cw.speed)
if self.cw.servertype == 1:
self.cw.sendcw(f"\x1b2{self.cw.speed}")
if self.cw.servertype == 2:
self.cw.set_winkeyer_speed(self.cw_speed.value())
return
if (
event.key() == Qt.Key.Key_Period
and modifier == Qt.KeyboardModifier.ControlModifier
):
freq = self.radio_state.get("vfoa")
selected_mode = self.radio_state.get("mode")
if selected_mode == "CW":
deltaf = 20
elif selected_mode in ["LSB", "USB", "SSB"]:
deltaf = 100
else:
deltaf = 0
vfo = int(freq) + deltaf
if self.rig_control:
self.rig_control.set_vfo(vfo)
return
if (
event.key() == Qt.Key.Key_Comma
and modifier == Qt.KeyboardModifier.ControlModifier
):
freq = self.radio_state.get("vfoa")
selected_mode = self.radio_state.get("mode")
if selected_mode == "CW":
deltaf = 20
elif selected_mode in ["LSB", "USB", "SSB"]:
deltaf = 100
else:
deltaf = 0
vfo = int(freq) - deltaf
if self.rig_control:
self.rig_control.set_vfo(vfo)
return
if event.key() == Qt.Key.Key_Tab or event.key() == Qt.Key.Key_Backtab:
if self.sent.hasFocus():
logger.debug("From sent")
if modifier == Qt.KeyboardModifier.ShiftModifier:
prev_tab = self.tab_prev.get(self.sent)
prev_tab.setFocus()
prev_tab.deselect()
prev_tab.end(False)
else:
next_tab = self.tab_next.get(self.sent)
next_tab.setFocus()
next_tab.deselect()
next_tab.end(False)
self.highlight_599(next_tab)
return
if self.receive.hasFocus():
logger.debug("From receive")
if modifier == Qt.KeyboardModifier.ShiftModifier:
prev_tab = self.tab_prev.get(self.receive)
prev_tab.setFocus()
prev_tab.deselect()
prev_tab.end(False)
self.highlight_599(prev_tab)
else:
next_tab = self.tab_next.get(self.receive)
next_tab.setFocus()
next_tab.deselect()
next_tab.end(False)
return
if self.other_1.hasFocus():
logger.debug("From other_1")
if modifier == Qt.KeyboardModifier.ShiftModifier:
prev_tab = self.tab_prev.get(self.other_1)
prev_tab.setFocus()
prev_tab.deselect()
prev_tab.end(False)
self.highlight_599(prev_tab)
else:
next_tab = self.tab_next.get(self.other_1)
next_tab.setFocus()
next_tab.deselect()
next_tab.end(False)
return
if self.other_2.hasFocus():
logger.debug("From other_2")
if modifier == Qt.KeyboardModifier.ShiftModifier:
prev_tab = self.tab_prev.get(self.other_2)
prev_tab.setFocus()
prev_tab.deselect()
prev_tab.end(False)
self.highlight_599(prev_tab)
else:
next_tab = self.tab_next.get(self.other_2)
next_tab.setFocus()
next_tab.deselect()
next_tab.end(False)
return
if self.callsign.hasFocus():
logger.debug("From callsign")
self.check_callsign(self.callsign.text())
self.check_dupe(self.callsign.text())
if modifier == Qt.KeyboardModifier.ShiftModifier:
prev_tab = self.tab_prev.get(self.callsign)
prev_tab.setFocus()
prev_tab.deselect()
prev_tab.end(False)
else:
text = self.callsign.text()
text = text.upper()
cmd = {}
cmd["cmd"] = "LOOKUP_CALL"
cmd["call"] = text
if self.lookup_service:
self.lookup_service.msg_from_main(cmd)
next_tab = self.tab_next.get(self.callsign)
next_tab.setFocus()
next_tab.deselect()
next_tab.end(False)
self.highlight_599(next_tab)
return
if event.key() == Qt.Key.Key_F1:
if event.modifiers() == Qt.KeyboardModifier.ShiftModifier:
self.set_running(True)
# self.make_button_blue(self.F1)
self.leftdot.show()
self.cwprogressBar.setValue(100)
self.cwprogressBar.show()
self.auto_cq = True
self.auto_cq_then = datetime.datetime.now()
self.auto_cq_time = datetime.datetime.now() + datetime.timedelta(
milliseconds=self.auto_cq_delay
)
self.process_function_key(self.F1)
self.mark_cq()
return
if event.key() == Qt.Key.Key_F2:
self.process_function_key(self.F2)
return
if event.key() == Qt.Key.Key_F3:
self.process_function_key(self.F3)
return
if event.key() == Qt.Key.Key_F4:
self.process_function_key(self.F4)
return
if event.key() == Qt.Key.Key_F5:
self.process_function_key(self.F5)
return
if event.key() == Qt.Key.Key_F6:
self.process_function_key(self.F6)
return
if event.key() == Qt.Key.Key_F7:
self.process_function_key(self.F7)
return
if event.key() == Qt.Key.Key_F8:
self.process_function_key(self.F8)
return
if event.key() == Qt.Key.Key_F9:
self.process_function_key(self.F9)
return
if event.key() == Qt.Key.Key_F10:
self.process_function_key(self.F10)
return
if event.key() == Qt.Key.Key_F11:
self.process_function_key(self.F11)
return
if event.key() == Qt.Key.Key_F12:
self.process_function_key(self.F12)
def highlight_599(self, field: QLineEdit) -> None:
if field.text() == "599" and self.pref.get("edit_rst", False):
field.setSelection(1, 1)
def set_window_title(self) -> None:
"""
Set window title based on current state.
"""
vfoa = self.radio_state.get("vfoa", "")
if vfoa:
try:
vfoa = int(vfoa) / 1000
except ValueError:
vfoa = 0.0
else:
vfoa = 0.0
contest_name = ""
if self.contest:
contest_name = self.contest.name
line = (
f"vfoa:{round(vfoa,2)} "
f"mode:{self.radio_state.get('mode', '')} "
f"OP:{self.current_op} {contest_name} "
f"{self.spaceweather} "
f"- Not1MM v{__version__}"
)
self.setWindowTitle(line)
def send_worked_list(self) -> None:
"""
Send message containing worked contacts and bands
Parameters
----------
None
Returns
-------
None
"""
cmd = {}
cmd["cmd"] = "WORKED"
cmd["worked"] = self.worked_list
logger.debug("%s", f"{cmd}")
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
def clearinputs(self) -> None:
"""
Clears the text input fields and sets focus to callsign field.
Parameters
----------
None
Returns
-------
None
"""
self.dupe_indicator.hide()
self.callsign.setStyleSheet("")
self.contact = self.database.empty_contact.copy()
self.heading_distance.setText("")
self.history_info.setText("")
self.dx_entity.setText("")
if self.contest:
mults = self.contest.show_mults(self)
qsos = self.contest.show_qso(self)
multstring = f"{qsos}/{mults}"
self.mults.setText(multstring)
score = self.contest.calc_score(self)
self.score.setText(str(score))
self.contest.reset_label(self)
if (
self.contest.name != "ICWC Medium Speed Test"
and self.contest.name != "RAEM"
and self.contest.name != "QSO PARTY SN"
):
match self.current_mode:
case "LSB" | "USB" | "SSB" | "FM" | "AM":
self.sent.setText("59")
self.receive.setText("59")
case "CW" | "CW-U" | "CW-L" | "CW-R" | "CWR":
self.sent.setText("599")
self.receive.setText("599")
case (
"FT8"
| "FT4"
| "RTTY"
| "PSK31"
| "FSK441"
| "MSK144"
| "JT65"
| "JT9"
| "Q65"
| "PKTUSB"
| "PKTLSB"
):
self.sent.setText("599")
self.receive.setText("599")
case _:
self.sent.setText("")
self.receive.setText("")
# end match
else:
self.sent.setText("")
self.receive.setText("")
self.callsign.clear()
self.other_1.clear()
self.other_2.clear()
self.callsign.setFocus()
cmd = {}
cmd["cmd"] = "CALLCHANGED"
cmd["call"] = ""
if self.log_window:
self.log_window.msg_from_main(cmd)
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
if self.check_window:
self.check_window.msg_from_main(cmd)
def save_contact(self) -> None:
"""
Save contact to database.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("saving contact")
if self.contest is None:
self.show_message_box("You have no contest defined...")
return
if len(self.callsign.text()) < 3:
return
if not any(char.isdigit() for char in self.callsign.text()):
return
if not any(char.isalpha() for char in self.callsign.text()):
return
self.contact["TS"] = datetime.datetime.now(datetime.timezone.utc).isoformat(
" "
)[:19]
self.contact["Call"] = self.callsign.text()
if self.contact.get("Mode") not in (
"CONTESTI",
"DOMINO",
"FSQ",
"FT8",
"FT4",
"HELL",
"IFKP",
"RTTY",
"PSK",
"PSK31",
"FSK441",
"MFSK",
"MSK144",
"MT63",
"OLIVIA",
"JS8",
"JT65",
"JT9",
"Q65",
"SCAMP",
"THOR",
"THRB",
):
self.contact["Freq"] = round(
float(self.radio_state.get("vfoa", 0.0)) / 1000, 2
)
self.contact["QSXFreq"] = round(
float(self.radio_state.get("vfoa", 0.0)) / 1000, 2
)
self.contact["Mode"] = self.radio_state.get("mode", "")
self.contact["Freq"] = round(float(self.radio_state.get("vfoa", 0.0)) / 1000, 2)
self.contact["QSXFreq"] = round(
float(self.radio_state.get("vfoa", 0.0)) / 1000, 2
)
self.contact["ContestName"] = self.contest.cabrillo_name
self.contact["ContestNR"] = self.pref.get("contest", "0")
self.contact["StationPrefix"] = self.station.get("Call", "")
self.contact["WPXPrefix"] = calculate_wpx_prefix(self.callsign.text())
self.contact["IsRunQSO"] = self.radioButton_run.isChecked()
self.contact["Operator"] = self.current_op
if self.RoverLocation:
self.contact["RoverLocation"] = self.RoverLocation
else:
self.contact["RoverLocation"] = self.station.get("RoverQTH", "").upper()
self.contact["NetBiosName"] = socket.gethostname()
self.contact["IsOriginal"] = 1
self.contact["ID"] = uuid.uuid4().hex
self.contest.set_contact_vars(self)
self.contact["Points"] = self.contest.points(self)
debug_output = f"{self.contact}"
logger.debug(debug_output)
if self.n1mm:
logger.debug("packets %s", f"{self.n1mm.send_contact_packets}")
if self.n1mm.send_contact_packets:
self.n1mm.contact_info["timestamp"] = self.contact["TS"]
self.n1mm.contact_info["oldcall"] = self.n1mm.contact_info["call"] = (
self.contact["Call"]
)
self.n1mm.contact_info["txfreq"] = self.n1mm.contact_info["rxfreq"] = (
self.n1mm.radio_info["Freq"]
)
self.n1mm.contact_info["mode"] = self.contact["Mode"]
self.n1mm.contact_info["contestname"] = self.contact[
"ContestName"
].replace("-", "")
self.n1mm.contact_info["contestnr"] = self.contact["ContestNR"]
self.n1mm.contact_info["stationprefix"] = self.contact["StationPrefix"]
self.n1mm.contact_info["wpxprefix"] = self.contact["WPXPrefix"]
self.n1mm.contact_info["IsRunQSO"] = self.contact["IsRunQSO"]
self.n1mm.contact_info["operator"] = self.contact["Operator"]
self.n1mm.contact_info["mycall"] = self.contact["Operator"]
self.n1mm.contact_info["StationName"] = self.n1mm.contact_info[
"NetBiosName"
] = self.contact["NetBiosName"]
self.n1mm.contact_info["IsOriginal"] = self.contact["IsOriginal"]
self.n1mm.contact_info["ID"] = self.contact["ID"]
self.n1mm.contact_info["points"] = self.contact["Points"]
self.n1mm.contact_info["snt"] = self.contact["SNT"]
self.n1mm.contact_info["rcv"] = self.contact["RCV"]
self.n1mm.contact_info["sntnr"] = self.contact["SentNr"]
self.n1mm.contact_info["rcvnr"] = self.contact["NR"]
self.n1mm.contact_info["ismultiplier1"] = self.contact.get(
"IsMultiplier1", 0
)
self.n1mm.contact_info["ismultiplier2"] = self.contact.get(
"IsMultiplier2", 0
)
self.n1mm.contact_info["ismultiplier3"] = self.contact.get(
"IsMultiplier3", 0
)
self.n1mm.contact_info["section"] = self.contact["Sect"]
self.n1mm.contact_info["prec"] = self.contact["Prec"]
self.n1mm.contact_info["ck"] = self.contact["CK"]
self.n1mm.contact_info["zn"] = self.contact["ZN"]
self.n1mm.contact_info["power"] = self.contact["Power"]
self.n1mm.contact_info["band"] = self.contact["Band"]
logger.debug("%s", f"{self.n1mm.contact_info}")
self.n1mm.send_contact_info()
self.database.log_contact(self.contact)
if not self.pref["run_state"]: # in S&P mode, put the contact into the bandmap
self.mark_spot(comment=self.current_mode)
# Copy the last contact so it can be sent to the cluster:
self.previous_contact = dict(self.contact)
self.current_sn = None
# server
if self.pref.get("useserver", False) is True:
stale = datetime.datetime.now() + datetime.timedelta(seconds=30)
self.contact["cmd"] = "POST"
self.contact["expire"] = stale.isoformat()
self.server_commands.append(self.contact)
try:
self.server_channel.send_as_json(self.contact)
except OSError as err:
logging.warning("%s", err)
self.worked_list = self.database.get_calls_and_bands()
self.send_worked_list()
self.clearinputs()
self.update_rtc_xml()
cmd = {}
cmd["cmd"] = "UPDATELOG"
if self.log_window:
self.log_window.msg_from_main(cmd)
if self.check_window:
self.check_window.msg_from_main(cmd)
if self.statistics_window:
self.statistics_window.msg_from_main(cmd)
if self.dxcc_window:
self.dxcc_window.msg_from_main(cmd)
if self.zone_window:
self.zone_window.msg_from_main(cmd)
if self.rate_window:
self.rate_window.msg_from_main(cmd)
def update_rtc_xml(self) -> None:
"""Update RTC XML"""
if self.pref.get("send_rtc_scores", False):
if self.contest is None:
return
if hasattr(self.contest, "online_score_xml"):
if self.rtc_service is not None:
self.rtc_service.xml = self.contest.online_score_xml(self)
def new_contest_dialog(self) -> None:
"""
Show new contest dialog.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("New contest Dialog")
self.contest_dialog = NewContest(fsutils.APP_DATA_PATH)
if self.current_palette:
self.contest_dialog.setPalette(self.current_palette)
self.contest_dialog.exchange.setPalette(self.current_palette)
self.contest_dialog.operators.setPalette(self.current_palette)
self.contest_dialog.accepted.connect(self.save_contest)
self.contest_dialog.dateTimeEdit.setDate(QtCore.QDate.currentDate())
self.contest_dialog.dateTimeEdit.setCalendarPopup(True)
self.contest_dialog.dateTimeEdit.setTime(QtCore.QTime(0, 0))
self.contest_dialog.power.setCurrentText("LOW")
self.contest_dialog.station.setCurrentText("FIXED")
self.contest_dialog.open()
def save_contest(self) -> None:
"""
Save Contest to database.
Parameters
----------
None
Returns
-------
None
"""
next_number = self.database.get_next_contest_nr()
contest = {}
contest["ContestName"] = (
self.contest_dialog.contest.currentText().lower().replace(" ", "_")
)
contest["StartDate"] = self.contest_dialog.dateTimeEdit.dateTime().toString(
"yyyy-MM-dd hh:mm:ss"
)
contest["OperatorCategory"] = self.contest_dialog.operator_class.currentText()
contest["BandCategory"] = self.contest_dialog.band.currentText()
contest["PowerCategory"] = self.contest_dialog.power.currentText()
contest["ModeCategory"] = self.contest_dialog.mode.currentText()
contest["OverlayCategory"] = self.contest_dialog.overlay.currentText()
# contest['ClaimedScore'] = self.contest_dialog.
contest["Operators"] = self.contest_dialog.operators.text()
contest["Soapbox"] = self.contest_dialog.soapbox.toPlainText()
contest["SentExchange"] = self.contest_dialog.exchange.text()
contest["ContestNR"] = next_number.get("count", 1)
self.pref["contest"] = next_number.get("count", 1)
# contest['SubType'] = self.contest_dialog.
contest["StationCategory"] = self.contest_dialog.station.currentText()
contest["AssistedCategory"] = self.contest_dialog.assisted.currentText()
contest["TransmitterCategory"] = self.contest_dialog.transmitter.currentText()
# contest['TimeCategory'] = self.contest_dialog.
logger.debug("%s", f"{contest}")
self.database.add_contest(contest)
self.write_preference()
self.load_contest()
def edit_station_settings(self) -> None:
"""
Show settings dialog for station.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("Station Settings selected")
self.settings_dialog = EditStation(fsutils.APP_DATA_PATH)
if self.current_palette:
self.settings_dialog.setPalette(self.current_palette)
self.settings_dialog.accepted.connect(self.save_settings)
self.settings_dialog.Call.setText(self.station.get("Call", ""))
self.settings_dialog.Name.setText(self.station.get("Name", ""))
self.settings_dialog.Address1.setText(self.station.get("Street1", ""))
self.settings_dialog.Address2.setText(self.station.get("Street2", ""))
self.settings_dialog.City.setText(self.station.get("City", ""))
self.settings_dialog.State.setText(self.station.get("State", ""))
self.settings_dialog.Zip.setText(self.station.get("Zip", ""))
self.settings_dialog.Country.setText(self.station.get("Country", ""))
self.settings_dialog.GridSquare.setText(self.station.get("GridSquare", ""))
self.settings_dialog.CQZone.setText(str(self.station.get("CQZone", "")))
self.settings_dialog.ITUZone.setText(str(self.station.get("IARUZone", "")))
self.settings_dialog.License.setText(self.station.get("LicenseClass", ""))
self.settings_dialog.Latitude.setText(str(self.station.get("Latitude", "")))
self.settings_dialog.Longitude.setText(str(self.station.get("Longitude", "")))
self.settings_dialog.StationTXRX.setText(self.station.get("stationtxrx", ""))
self.settings_dialog.Power.setText(self.station.get("SPowe", ""))
self.settings_dialog.Antenna.setText(self.station.get("SAnte", ""))
self.settings_dialog.AntHeight.setText(self.station.get("SAntH1", ""))
self.settings_dialog.ASL.setText(self.station.get("SAntH2", ""))
self.settings_dialog.ARRLSection.setText(self.station.get("ARRLSection", ""))
self.settings_dialog.RoverQTH.setText(self.station.get("RoverQTH", ""))
self.settings_dialog.Club.setText(self.station.get("Club", ""))
self.settings_dialog.Email.setText(self.station.get("Email", ""))
self.settings_dialog.open()
def save_settings(self) -> None:
"""
Save Station settings to database.
Parameters
----------
None
Returns
-------
None
"""
cs = self.settings_dialog.Call.text()
self.station = {}
self.station["Call"] = cs.upper()
self.station["Name"] = self.settings_dialog.Name.text().title()
self.station["Street1"] = self.settings_dialog.Address1.text().title()
self.station["Street2"] = self.settings_dialog.Address2.text().title()
self.station["City"] = self.settings_dialog.City.text().title()
self.station["State"] = self.settings_dialog.State.text().upper()
self.station["Zip"] = self.settings_dialog.Zip.text()
self.station["Country"] = self.settings_dialog.Country.text().title()
self.station["GridSquare"] = self.settings_dialog.GridSquare.text()
self.station["CQZone"] = self.settings_dialog.CQZone.text()
self.station["IARUZone"] = self.settings_dialog.ITUZone.text()
self.station["LicenseClass"] = self.settings_dialog.License.text().title()
self.station["Latitude"] = self.settings_dialog.Latitude.text()
self.station["Longitude"] = self.settings_dialog.Longitude.text()
self.station["STXeq"] = self.settings_dialog.StationTXRX.text()
self.station["SPowe"] = self.settings_dialog.Power.text()
self.station["SAnte"] = self.settings_dialog.Antenna.text()
self.station["SAntH1"] = self.settings_dialog.AntHeight.text()
self.station["SAntH2"] = self.settings_dialog.ASL.text()
self.station["ARRLSection"] = self.settings_dialog.ARRLSection.text().upper()
self.station["RoverQTH"] = self.settings_dialog.RoverQTH.text()
self.station["Club"] = self.settings_dialog.Club.text()
self.station["Email"] = self.settings_dialog.Email.text()
self.database.add_station(self.station)
if self.rotator_window is not None:
self.rotator_window.set_mygrid(self.settings_dialog.GridSquare.text())
self.settings_dialog.close()
if self.current_op == "":
self.current_op = self.station.get("Call", "")
self.voice_process.current_op = self.current_op
self.make_op_dir()
contest_count = self.database.fetch_all_contests()
if len(contest_count) == 0:
self.new_contest_dialog()
def edit_macro(self, function_key: str) -> None:
"""
Show edit macro dialog for function key.
Parameters
----------
function_key : str
Function key to edit.
Returns
-------
None
"""
self.edit_macro_dialog = EditMacro(function_key, fsutils.APP_DATA_PATH)
if self.current_palette:
self.edit_macro_dialog.setPalette(self.current_palette)
self.edit_macro_dialog.accepted.connect(self.edited_macro)
self.edit_macro_dialog.open()
def edited_macro(self) -> None:
"""
Save edited macro to database.
Parameters
----------
None
Returns
-------
None
"""
self.edit_macro_dialog.function_key.setText(
self.edit_macro_dialog.macro_label.text()
)
self.edit_macro_dialog.function_key.setToolTip(
self.edit_macro_dialog.the_macro.text()
)
self.edit_macro_dialog.close()
if self.radioButton_run.isChecked():
rm = "R"
else:
rm = "S"
_, _, new_label = self.edit_macro_dialog.macro_label.text().partition(":")
fkey, _, old_label = self.edit_macro_dialog.old_label.partition(":")
new_label = new_label.strip()
old_label = old_label.strip()
old_string = self.edit_macro_dialog.old_macro
new_string = f"{self.edit_macro_dialog.the_macro.text()}"
macro_file = str(self.get_macro_filename())
try:
with open(macro_file, "r") as file:
content = file.read()
# Perform the replacement
new_content = content.replace(
f"{rm}|{fkey}|{old_label}|{old_string}",
f"{rm}|{fkey}|{new_label}|{new_string}",
)
# Write the modified content back to the file
with open(macro_file, "w") as file:
file.write(new_content)
except Exception as e:
logger.error(f"Failed to update macro file: {macro_file}. Error: {e}")
def format_serial(self, serial: str) -> str:
"""
Pad serial number to desired length (all modes) and do CW cut numbers replacements.
"""
serial = serial.lstrip("0")
if self.radio_state.get("mode") == "CW":
serial = (
serial.replace("1", self.pref.get("cwserial_1", "1"))
.replace("9", self.pref.get("cwserial_9", "9"))
.replace("0", self.pref.get("cwserial_0", "0"))
)
padding = self.pref.get("cwpaddingchar", "T")
else:
padding = "0"
serial = serial.rjust(self.pref.get("cwpaddinglength", 3), padding)
return serial
def format_rst(self, rst: str) -> str:
"""
Apply CW cut numbers to RST sent.
"""
if self.radio_state.get("mode") == "CW":
# Only send "E" if the full report is 599, we shouldn't end up with
# something mixed like "E8N"
if self.pref.get("cwsentrst", "5NN") == "ENN" and rst == "599":
return "ENN"
if self.pref.get("cwsentrst", "5NN") in ("5NN", "ENN"):
return rst.replace("9", "N")
return rst
def process_macro(self, macro: str) -> str:
"""
Process CW macro substitutions for contest.
Parameters
----------
macro : str
Macro to process.
Returns
-------
str
Processed macro.
"""
if self.current_sn is not None:
next_serial = str(self.current_sn)
else:
next_serial = ""
result = self.database.get_last_serial()
prev_serial = str(result.get("serial_nr", "1")).zfill(3)
macro = macro.upper()
macro = macro.replace( # handle EXCH first so it can contain more macros
"{EXCH}", self.contest_settings.get("SentExchange", "xxx")
)
macro = macro.replace("#", self.format_serial(next_serial))
macro = macro.replace("{MYCALL}", self.station.get("Call", ""))
macro = macro.replace("{HISCALL}", self.callsign.text())
macro = macro.replace("{OTHER1}", self.other_1.text())
macro = macro.replace("{OTHER2}", self.other_2.text())
macro = macro.replace("{SNT}", self.format_rst(self.sent.text()))
macro = macro.replace("{SENTNR}", self.format_serial(self.other_1.text()))
macro = macro.replace("{PREVNR}", self.format_serial(str(prev_serial)))
if "{TX}" in macro:
macro = macro.replace("{TX}", "")
self.ptt_on()
if "{RX}" in macro:
macro = macro.replace("{RX}", "")
self.ptt_off()
if "{TX/RX}" in macro:
macro = macro.replace("{TX/RX}", "")
if self.rig_control:
ptt_state = self.rig_control.get_ptt()
logger.debug(f"PTT State: {ptt_state} (type={type(ptt_state)})")
# Sometimes rigctl returns "PTT State: get_mode:|Mode: LSB|Passband: 2800|RPRT 0" ???
if str(ptt_state) == "0":
self.ptt_on()
else:
self.ptt_off()
if "{LOGIT}" in macro:
macro = macro.replace("{LOGIT}", "")
self.save_contact()
if "{MARK}" in macro:
macro = macro.replace("{MARK}", "")
self.mark_spot(comment=f"{self.current_mode} MARKED")
if "{SPOT}" in macro:
macro = macro.replace("{SPOT}", "")
self.spot_dx()
if "{RUN}" in macro:
macro = macro.replace("{RUN}", "")
self.set_running(True)
if "{SANDP}" in macro:
macro = macro.replace("{SANDP}", "")
self.set_running(False)
if "{WIPE}" in macro:
macro = macro.replace("{WIPE}", "")
self.clearinputs()
if "{VOICE1}" in macro:
macro = macro.replace("{VOICE1}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=1)
if "{VOICE2}" in macro:
macro = macro.replace("{VOICE2}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=2)
if "{VOICE3}" in macro:
macro = macro.replace("{VOICE3}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=3)
if "{VOICE4}" in macro:
macro = macro.replace("{VOICE4}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=4)
if "{VOICE5}" in macro:
macro = macro.replace("{VOICE5}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=5)
if "{VOICE6}" in macro:
macro = macro.replace("{VOICE6}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=6)
if "{VOICE7}" in macro:
macro = macro.replace("{VOICE7}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=7)
if "{VOICE8}" in macro:
macro = macro.replace("{VOICE8}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=8)
if "{VOICE9}" in macro:
macro = macro.replace("{VOICE9}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=9)
if "{VOICE10}" in macro:
macro = macro.replace("{VOICE10}", "")
if self.rig_control:
self.rig_control.sendvoicememory(memoryspot=10)
return macro
def ptt_on(self) -> None:
"""
Turn on ptt for rig.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("PTT On")
if self.rig_control:
# self.leftdot.setPixmap(self.greendot)
# app.processEvents()
self.rig_control.ptt_on()
def ptt_off(self) -> None:
"""
Turn off ptt for rig.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("PTT Off")
if self.rig_control:
# self.leftdot.setPixmap(self.reddot)
# app.processEvents()
self.rig_control.ptt_off()
def process_function_key(
self, function_key: QPushButton, rttysendrx: bool = True
) -> None:
"""
Called when a function key is clicked.
Parameters
----------
function_key : QPushButton
Function key to process.
rttysendrx : bool
Should a '^r' be appended.
Returns
-------
None
"""
logger.debug("Function Key: %s", function_key.text())
if function_key.toolTip()[0:3] == "RI:":
self.rig_control.cat.send_cat_string(function_key.toolTip()[3:])
return
if self.n1mm:
self.n1mm.radio_info["FunctionKeyCaption"] = function_key.text()
if self.radio_state.get("mode") in ["LSB", "USB", "SSB", "FM", "AM"]:
self.voice_process.voice_string(self.process_macro(function_key.toolTip()))
# self.voice_string(self.process_macro(function_key.toolTip()))
return
if self.radio_state.get("mode") in [
"RTTY",
"USB-D",
"LSB-D",
"PKTLSB",
"PKTUSB",
"DIGI-U",
"DIGI-L",
]:
self.fldigi_util.send_string(
self.process_macro(function_key.toolTip()), rxafter=rttysendrx
)
return
if self.cw:
if self.pref.get("cwtype") == 3 and self.rig_control is not None:
self.rig_control.sendcw(
self.process_macro(function_key.toolTip()) + " "
)
return
self.cw.sendcw(self.process_macro(function_key.toolTip()) + " ")
if self.pref.get("cwtype") == 2:
# I put this back in 'cause no one will know to update winkeyerserial.
time.sleep(0.2)
def set_running(self, run: bool) -> None:
"""Set Run/S&P. Avoid re-reading all state when nothing changed."""
if run != self.pref["run_state"]:
if run:
self.radioButton_run.setChecked(True)
else:
self.radioButton_sp.setChecked(True)
self.run_sp_buttons_clicked()
def toggle_run_sp(self) -> None:
"""Toggles the radioButton_run and radioButton_sp."""
self.set_running(not self.pref["run_state"])
def run_sp_buttons_clicked(self) -> None:
"""
Handle Run/S&P mode changes.
Parameters
----------
None
Returns
-------
None
"""
self.pref["run_state"] = self.radioButton_run.isChecked()
self.write_preference()
self.read_macros()
self.check_esm()
def write_preference(self) -> None:
"""
Write preferences to file.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("writepreferences")
try:
with open(fsutils.CONFIG_FILE, "wt", encoding="utf-8") as file_descriptor:
file_descriptor.write(dumps(self.pref, indent=4))
# logger.info("writing: %s", self.pref)
except (IOError, TypeError, ValueError) as exception:
logger.critical("writepreferences: %s", exception)
def readpreferences(self) -> None:
"""
Restore preferences if they exist, otherwise create some sane defaults.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("readpreferences")
try:
if os.path.exists(fsutils.CONFIG_FILE):
with open(
fsutils.CONFIG_FILE, "rt", encoding="utf-8"
) as file_descriptor:
try:
self.pref = loads(file_descriptor.read())
except (JSONDecodeError, TypeError):
logging.CRITICAL(
"There was an error parsing the preference file."
)
logger.info("%s", self.pref)
else:
logger.info("No preference file. Writing preference.")
with open(
fsutils.CONFIG_FILE, "wt", encoding="utf-8"
) as file_descriptor:
self.pref = self.pref_ref.copy()
file_descriptor.write(dumps(self.pref, indent=4))
logger.info("%s", self.pref)
except (IOError, TypeError, ValueError) as exception:
logger.critical("Error: %s", exception)
if self.pref.get("run_state", False) is True:
self.radioButton_run.setChecked(True)
else:
self.radioButton_sp.setChecked(True)
if self.pref.get("command_buttons", False) is True:
self.actionCommand_Buttons.setChecked(True)
else:
self.actionCommand_Buttons.setChecked(False)
if self.pref.get("cw_macros", False) is True:
self.actionCW_Macros.setChecked(True)
else:
self.actionCW_Macros.setChecked(False)
if self.pref.get("bands_modes", False) is True:
self.actionMode_and_Bands.setChecked(True)
else:
self.actionMode_and_Bands.setChecked(False)
cmd = {}
cmd["cmd"] = "REFRESH_LOOKUP"
if self.lookup_service:
self.lookup_service.msg_from_main(cmd)
try:
if self.rtc_thread.isRunning():
self.rtc_service.time_to_quit = True
self.rtc_thread.quit()
self.rtc_thread.wait(1000)
except (RuntimeError, AttributeError):
...
self.rtc_service = None
self.send_rtc_scores = self.pref.get("send_rtc_scores", False)
self.rtc_url = self.pref.get("rtc_url", "")
self.rtc_user = self.pref.get("rtc_user", "")
self.rtc_pass = self.pref.get("rtc_pass", "")
self.rtc_interval = self.pref.get("rtc_interval", 2)
try:
self.auto_cq_delay = int(self.pref.get("auto_cq_interval", 15)) * 1000
except ValueError:
self.auto_cq_delay = 15000
if self.pref.get("send_rtc_scores", False) is True:
self.rtc_service = RTCService()
self.rtc_service.moveToThread(self.rtc_thread)
self.rtc_thread.started.connect(self.rtc_service.run)
self.rtc_thread.finished.connect(self.rtc_service.deleteLater)
self.rtc_thread.start()
self.rtc_service.rtc_callback.connect(self.rtc_response)
try:
if self.radio_thread.isRunning():
self.rig_control.time_to_quit = True
self.radio_thread.quit()
self.radio_thread.wait(1000)
except (RuntimeError, AttributeError):
...
self.rig_control = None
self.fldigi_util = FlDigi_Comm()
if self.pref.get("useflrig", False) is True:
logger.debug(
"Using flrig: %s",
f"{self.pref.get('CAT_ip')} {self.pref.get('CAT_port')}",
)
self.rig_control = Radio(
"flrig",
self.pref.get("CAT_ip", "127.0.0.1"),
int(self.pref.get("CAT_port", 12345)),
)
elif self.pref.get("userigctld", False) is True:
logger.debug(
"Using rigctld: %s",
f"{self.pref.get('CAT_ip')} {self.pref.get('CAT_port')}",
)
self.rig_control = Radio(
"rigctld",
self.pref.get("CAT_ip", "127.0.0.1"),
int(self.pref.get("CAT_port", 4532)),
)
else:
self.rig_control = Radio(
"fake",
self.pref.get("CAT_ip", "127.0.0.1"),
int(self.pref.get("CAT_port", 0000)),
)
self.rig_control.delta = int(self.pref.get("CAT_polldelta", 555))
self.rig_control.moveToThread(self.radio_thread)
self.radio_thread.started.connect(self.rig_control.run)
self.radio_thread.finished.connect(self.rig_control.deleteLater)
self.rig_control.poll_callback.connect(self.poll_radio)
self.radio_thread.start()
self.cw = None
if (
self.pref.get("cwport")
and self.pref.get("cwip")
and self.pref.get("cwtype")
):
self.cw = CW(
int(self.pref.get("cwtype")),
self.pref.get("cwip"),
int(self.pref.get("cwport")),
)
self.cw_speed.setValue(int(self.pref.get("cw_speed", 20)))
self.cw.speed = int(self.pref.get("cw_speed", 20))
if self.cw.servertype == 2:
self.cw.set_winkeyer_speed(int(self.pref.get("cw_speed", 20)))
self.n1mm = None
if self.pref.get("send_n1mm_packets", False):
try:
self.n1mm = N1MM(
self.pref.get("n1mm_radioport", "127.0.0.1:12060"),
self.pref.get("n1mm_contactport", "127.0.0.1:12061"),
self.pref.get("n1mm_lookupport", "127.0.0.1:12060"),
self.pref.get("n1mm_scoreport", "127.0.0.1:12060"),
)
except ValueError:
logger.warning("%s", f"{ValueError}")
self.n1mm.send_radio_packets = self.pref.get("send_n1mm_radio", False)
self.n1mm.send_contact_packets = self.pref.get("send_n1mm_contact", False)
self.n1mm.send_lookup_packets = self.pref.get("send_n1mm_lookup", False)
self.n1mm.send_score_packets = self.pref.get("send_n1mm_score", False)
self.n1mm.radio_info["StationName"] = self.pref.get("n1mm_station_name", "")
if self.pref.get("useserver", False):
self.server_channel = Multicast(
multicast_group=self.pref.get("multicast_group", "239.1.1.1"),
multicast_port=self.pref.get("multicast_port", 2239),
interface_ip=self.pref.get("interface_ip", "0.0.0.0"),
)
self.server_channel.ready_read_connect(self.server_message)
self.show_command_buttons()
self.show_CW_macros()
# If bands list is empty fill it with HF.
if self.pref.get("bands", []) == []:
self.pref["bands"] = [
"160",
"80",
"40",
"20",
"15",
"10",
]
# Hide all the bands and then show only the wanted bands.
for _indicator in [
self.band_indicators_cw,
self.band_indicators_ssb,
self.band_indicators_rtty,
]:
for _bandind in _indicator.values():
_bandind.hide()
for band_to_show in self.pref.get("bands", []):
if band_to_show in _indicator:
_indicator[band_to_show].show()
fkey_dict = {
"F1": self.F1,
"F2": self.F2,
"F3": self.F3,
"F4": self.F4,
"F5": self.F5,
"F6": self.F6,
"F7": self.F7,
"F8": self.F8,
"F9": self.F9,
"F10": self.F10,
"F11": self.F11,
"F12": self.F12,
"DISABLED": None,
}
self.use_call_history = self.pref.get("use_call_history", False)
if self.use_call_history:
self.history_info.show()
else:
self.history_info.hide()
self.use_esm = self.pref.get("use_esm", False)
self.esm_dict["CQ"] = fkey_dict.get(self.pref.get("esm_cq", "DISABLED"))
self.esm_dict["EXCH"] = fkey_dict.get(self.pref.get("esm_exch", "DISABLED"))
self.esm_dict["QRZ"] = fkey_dict.get(self.pref.get("esm_qrz", "DISABLED"))
self.esm_dict["AGN"] = fkey_dict.get(self.pref.get("esm_agn", "DISABLED"))
self.esm_dict["HISCALL"] = fkey_dict.get(
self.pref.get("esm_hiscall", "DISABLED")
)
self.esm_dict["MYCALL"] = fkey_dict.get(self.pref.get("esm_mycall", "DISABLED"))
self.esm_dict["QSOB4"] = fkey_dict.get(self.pref.get("esm_qsob4", "DISABLED"))
self.update_rtc_xml()
if self.pref.get("useserver", False) is True:
self.server_icon.show()
self.server_icon.setPixmap(self.redserver)
else:
self.server_icon.hide()
if isinstance(self.rotator_window, RotatorWindow):
self.rotator_window.set_host_port(
host=self.pref.get(
"rotctld_address",
"127.0.0.1",
),
port=self.pref.get("rotctld_port", 4533),
)
def rtc_response(self, response: dict) -> None:
print(f"{response=}")
def cw_macros_state_changed(self) -> None:
"""
Menu item to show/hide macro buttons.
Parameters
----------
None
Returns
-------
None
"""
self.pref["cw_macros"] = self.actionCW_Macros.isChecked()
self.write_preference()
self.show_CW_macros()
def show_CW_macros(self) -> None:
"""
Show/Hide the macro buttons.
Parameters
----------
None
Returns
-------
None
"""
if self.pref.get("cw_macros"):
self.Button_Row1.show()
self.Button_Row2.show()
else:
self.Button_Row1.hide()
self.Button_Row2.hide()
def command_buttons_state_change(self) -> None:
"""
Menu item to show/hide command buttons
Parameters
----------
None
Returns
-------
None
"""
self.pref["command_buttons"] = self.actionCommand_Buttons_2.isChecked()
self.write_preference()
self.show_command_buttons()
def show_command_buttons(self) -> None:
"""
Show/Hide the command buttons depending on the preference.
Parameters
----------
None
Returns
-------
"""
if self.pref.get("command_buttons", False) is True:
self.Command_Buttons.show()
else:
self.Command_Buttons.hide()
def is_floatable(self, item: str) -> bool:
"""
Check to see if string can be a float.
Parameters
----------
item : str
The string to test.
Returns
-------
bool
True if string can be a float, False otherwise.
"""
if item.isnumeric():
return True
try:
_test = float(item)
except ValueError:
return False
return True
def other_1_changed(self) -> None:
"""
The text in the other_1 field has changed.
Strip out any spaces and set the text.
Parameters
----------
None
Returns
-------
None
"""
if self.contest:
if hasattr(self.contest, "advance_on_space"):
if self.contest.advance_on_space[3]:
text = self.other_1.text()
text = text.upper()
# position = self.other_1.cursorPosition()
stripped_text = text.strip().replace(" ", "")
self.other_1.setText(stripped_text)
# self.other_1.setCursorPosition(position)
if " " in text:
next_tab = self.tab_next.get(self.other_1)
next_tab.setFocus()
next_tab.deselect()
next_tab.end(False)
def other_2_changed(self) -> None:
"""
Text in other_2 has changed.
Strip out any spaces and set the text.
Parse the exchange if the contest is ARRL Sweepstakes.
Parameters
----------
None
Returns
-------
None
"""
if self.contest:
if "ARRL Sweepstakes" in self.contest.name:
self.contest.parse_exchange(self)
return
if hasattr(self.contest, "call_parse_exchange_on_edit"):
if self.contest.advance_on_space:
self.contest.parse_exchange(self)
if hasattr(self.contest, "advance_on_space"):
if self.contest.advance_on_space[4]:
text = self.other_2.text()
text = text.upper()
# position = self.other_2.cursorPosition()
stripped_text = text.strip().replace(" ", "")
self.other_2.setText(stripped_text)
# self.other_2.setCursorPosition(position)
if " " in text:
next_tab = self.tab_next.get(self.other_2)
next_tab.setFocus()
next_tab.deselect()
next_tab.end(False)
def callsign_changed(self) -> None:
"""
Called when text in the callsign field has changed.
Strip out any spaces and set the text.
Check if the field contains a command.
Parameters
----------
None
Returns
-------
None
"""
if self.auto_cq is True:
self.stop_cw()
self.get_sn()
if self.pref.get("sandpqsy") is True and self.radioButton_sp.isChecked():
self.sandpfreq = int(self.radio_state.get("vfoa", 0))
text = self.callsign.text()
text = text.upper()
position = self.callsign.cursorPosition()
stripped_text = text.strip().replace(" ", "")
self.callsign.setText(stripped_text)
self.callsign.setCursorPosition(position)
if " " in text:
if stripped_text in ["CW", "RTTY", "SSB", "FM", "AM", "LSB", "USB"]:
self.change_mode(stripped_text)
return
if stripped_text == "OPON":
self.get_opon()
self.clearinputs()
return
if stripped_text == "ROVE":
self.get_rover()
self.clearinputs()
return
if stripped_text == "HELP":
self.show_help_dialog()
self.clearinputs()
return
if self.is_floatable(stripped_text):
self.change_freq(stripped_text)
self.clearinputs()
return
cmd = {}
cmd["cmd"] = "LOOKUP_CALL"
cmd["call"] = stripped_text
if self.lookup_service:
self.lookup_service.msg_from_main(cmd)
self.next_field.setFocus()
if self.contest:
if self.use_call_history and hasattr(
self.contest, "check_call_history"
):
self.contest.check_call_history(self)
if "CQ WW" in self.contest.name or "IARU HF" in self.contest.name:
self.contest.prefill(self)
return
cmd = {}
cmd["cmd"] = "CALLCHANGED"
cmd["call"] = stripped_text
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
if self.log_window:
self.log_window.msg_from_main(cmd)
if self.check_window:
self.check_window.msg_from_main(cmd)
self.dupe_indicator.hide()
self.callsign.setStyleSheet("")
if len(stripped_text) >= 3:
self.check_callsign(stripped_text)
self.check_dupe(stripped_text)
if self.contest:
if self.use_call_history and hasattr(
self.contest, "populate_history_info_line"
):
self.contest.populate_history_info_line(self)
def change_freq(self, stripped_text: str) -> None:
"""
Change Radios VFO to given frequency in Khz.
Parameters
----------
stripped_text: str
Stripped of any spaces.
Returns
-------
None
"""
vfo = float(stripped_text)
vfo = int(vfo * 1000)
if self.rig_control:
self.rig_control.set_vfo(vfo)
return
band = getband(str(vfo))
self.set_band_indicator(band)
self.radio_state["vfoa"] = vfo
self.radio_state["band"] = band
self.contact["Band"] = get_logged_band(str(vfo))
self.set_window_title()
self.clearinputs()
cmd = {}
cmd["cmd"] = "RADIO_STATE"
cmd["band"] = band
cmd["vfoa"] = vfo
if self.bandmap_window:
self.bandmap_window.msg_from_main(cmd)
def change_mode(self, mode: str, intended_freq: int | None = None) -> None:
"""
Change mode to given mode.
Send the new mode to the rig control.
Set the band indicator.
Set the window title.
Clear the inputs.
Read the CW macros.
Parameters
----------
mode : str
Mode to change to.
Returns
-------
None
"""
if mode in ("CW", "CW-U", "CW-L", "CWR"):
if self.rig_control:
if self.rig_control.online:
self.rig_control.set_mode(self.rig_control.last_cw_mode)
if self.pref.get("cwtype") == 3 and self.rig_control is not None:
if self.rig_control.interface == "flrig":
self.cwspeed_spinbox_changed()
self.rig_control.cat.set_flrig_cw_send(True)
else:
self.setmode("CW")
self.radio_state["mode"] = "CW"
band = getband(str(self.radio_state.get("vfoa", "0.0")))
self.set_band_indicator(band)
self.set_window_title()
self.clearinputs()
self.read_macros()
return
if mode in (
"DIGI-U",
"DIGI-L",
"RTTY",
"RTTY-R",
"LSB-D",
"USB-D",
"AM-D",
"FM-D",
):
if self.rig_control:
if self.rig_control.online:
self.rig_control.set_mode(self.rig_control.last_data_mode)
else:
self.radio_state["mode"] = "RTTY"
self.setmode("RTTY")
band = getband(str(self.radio_state.get("vfoa", "0.0")))
self.set_band_indicator(band)
self.set_window_title()
self.clearinputs()
self.read_macros()
return
if mode == "SSB":
if intended_freq:
freq = intended_freq
else:
freq = int(self.radio_state.get("vfoa", 0))
if freq > 10000000:
self.radio_state["mode"] = "USB"
else:
self.radio_state["mode"] = "LSB"
if self.rig_control:
if self.rig_control.online:
self.rig_control.set_mode(self.radio_state.get("mode"))
else:
self.setmode("SSB")
band = getband(str(self.radio_state.get("vfoa", "0.0")))
self.set_band_indicator(band)
self.set_window_title()
self.clearinputs()
self.read_macros()
return
if mode in ["AM", "FM", "LSB", "USB"]:
if self.rig_control:
if self.rig_control.online:
self.rig_control.set_mode(mode)
else:
self.setmode(mode)
band = getband(str(self.radio_state.get("vfoa", "0.0")))
self.set_band_indicator(band)
self.set_window_title()
self.clearinputs()
self.read_macros()
def check_callsign(self, callsign: str) -> None:
"""
Check callsign as it's being entered in the big_cty index.
Get DX entity, CQ, ITU and continent.
Geographic information. Distance and Heading.
Parameters
----------
callsign : str
Callsign to check.
Returns
-------
None
"""
result = self.cty_lookup(callsign)
if result is not None:
try:
a = result.get(next(iter(result)))
except (StopIteration, AttributeError):
return
entity = a.get("entity", "")
cq = a.get("cq", "")
itu = a.get("itu", "")
continent = a.get("continent")
lat = float(a.get("lat", "0.0"))
lon = float(a.get("long", "0.0"))
lon = lon * -1 # cty.dat file inverts longitudes
primary_pfx = a.get("primary_pfx", "")
heading = bearing_with_latlon(self.station.get("GridSquare"), lat, lon)
kilometers = distance_with_latlon(self.station.get("GridSquare"), lat, lon)
self.heading_distance.setText(
f"Regional Hdg {heading}° LP {reciprocal(heading)}° / "
f"distance {int(kilometers*0.621371)}mi {kilometers}km"
)
if self.rotator_window is not None:
self.rotator_window.set_requested_azimuth(float(heading))
self.contact["CountryPrefix"] = primary_pfx
self.contact["ZN"] = int(cq)
if self.contest:
if self.contest.name in ("IARU HF", "LZ DX"):
self.contact["ZN"] = int(itu)
self.contact["Continent"] = continent
self.dx_entity.setText(
f"{primary_pfx}: {continent}/{entity} cq:{cq} itu:{itu}"
)
if self.dxcc_window:
cmd = {}
cmd["cmd"] = "SCROLLTODXCC"
cmd["dxcc"] = primary_pfx
self.dxcc_window.msg_from_main(cmd)
if self.zone_window:
cmd = {}
cmd["cmd"] = "SCROLLTOZone"
cmd["cq"] = cq
cmd["itu"] = itu
self.zone_window.msg_from_main(cmd)
if len(callsign) > 2:
if self.contest:
if (
"CQ WW" not in self.contest.name
and "IARU HF" not in self.contest.name
):
self.contest.prefill(self)
def check_dupe(self, call: str) -> bool:
# TODO multi multi
"""Checks if a callsign is a dupe on current band/mode."""
if self.contest is None:
self.show_message_box("You have no contest loaded.")
return False
self.contest.predupe(self)
band = float(get_logged_band(str(self.radio_state.get("vfoa", 0.0))))
mode = self.radio_state.get("mode", "")
debugline = (
f"Call: {call} Band: {band} Mode: {mode} Dupetype: {self.contest.dupe_type}"
)
logger.debug("%s", debugline)
if (
self.pref.get("useserver", False) is True
and self.contest_settings.get("OperatorCategory", "") in ("MULTI-OP")
and self.contest_settings.get("TransmitterCategory", "")
not in ("ONE", "SWL")
):
cmd = {}
cmd["cmd"] = "ISDUPE"
cmd["Operator"] = self.current_op
cmd["NetBiosName"] = socket.gethostname()
cmd["Call"] = call
cmd["Band"] = band
cmd["Mode"] = mode
try:
self.server_channel.send_as_json(cmd)
except OSError as err:
logging.warning("%s", err)
else:
if self.contest.dupe_type == 1:
result = self.database.check_dupe(call)
if self.contest.dupe_type == 2:
result = self.database.check_dupe_on_band(call, band)
if self.contest.dupe_type == 3:
result = self.database.check_dupe_on_band_mode(call, band, mode)
if self.contest.dupe_type == 4:
result = {"isdupe": False}
if self.contest.dupe_type == 5:
result = {"isdupe": False} # in case contest has no function.
if not hasattr(self.contest, "check_dupe"):
result = self.contest.specific_contest_check_dupe(self, call)
debugline = f"{result}"
logger.debug("%s", debugline)
self.contact_is_dupe = result.get("isdupe", False)
if bool(result.get("isdupe", False)) is not False:
self.dupe_indicator.show()
self.callsign.setStyleSheet("color: red;")
else:
self.dupe_indicator.hide()
self.callsign.setStyleSheet("")
def setmode(self, mode: str) -> None:
"""Call when the mode changes."""
if mode in ("CW", "CW-U", "CW-L", "CWR", "CW-R"):
if self.current_mode != "CW":
self.current_mode = "CW"
if self.contest:
if self.contest.name != "QSO_PARTY_SN":
self.sent.setText("599")
self.receive.setText("599")
self.read_macros()
if self.contest.name == "ICWC Medium Speed Test":
self.contest.prefill(self)
return
if mode in ("LSB", "USB", "SSB", "FM", "AM"):
if self.current_mode != "SSB":
self.current_mode = "SSB"
if self.contest and self.contest.name != "QSO_PARTY_SN":
self.sent.setText("59")
self.receive.setText("59")
self.read_macros()
return
if mode in (
"FT8",
"FT4",
"RTTY",
"PSK31",
"FSK441",
"MSK144",
"JT65",
"JT9",
"Q65",
"PKTUSB",
"PKTLSB",
"DIGI-U",
"DIGI-L",
):
if self.current_mode != "RTTY":
self.current_mode = "RTTY"
if self.contest and self.contest.name != "QSO_PARTY_SN":
self.sent.setText("599")
self.receive.setText("599")
self.read_macros()
# TODO
def get_rover(self) -> None:
self.rover_dialog = Rove(fsutils.APP_DATA_PATH)
if self.current_palette:
self.rover_dialog.setPalette(self.current_palette)
self.rover_dialog.accepted.connect(self.new_rov)
self.rover_dialog.open()
def new_rov(self):
if self.rover_dialog.NewLocation.text():
self.RoverLocation = self.rover_dialog.NewLocation.text().upper()
logger.debug("New RoverLocation: %s", self.RoverLocation)
self.rover_dialog.close()
def get_opon(self) -> None:
"""
Ctrl+O Open the OPON dialog.
Parameters
----------
None
Returns
-------
None
"""
self.opon_dialog = OpOn(fsutils.APP_DATA_PATH)
if self.current_palette:
self.opon_dialog.setPalette(self.current_palette)
self.opon_dialog.accepted.connect(self.new_op)
self.opon_dialog.open()
def new_op(self) -> None:
"""
Called when the user clicks the OK button on the OPON dialog.
Create the new directory and copy the phonetic files.
Parameters
----------
None
Returns
-------
None
"""
if self.opon_dialog.NewOperator.text():
self.current_op = self.opon_dialog.NewOperator.text().upper()
self.voice_process.current_op = self.current_op
if self.bandmap_window:
self.bandmap_window.callsignField.setText(self.current_op)
if self.chat_window:
self.chat_window.mycall = self.current_op
self.opon_dialog.close()
logger.debug("New Op: %s", self.current_op)
self.make_op_dir()
self.set_window_title()
def make_op_dir(self) -> None:
"""
Create OP directory if it does not exist.
Copy the phonetic files to the new directory.
Parameters
----------
None
Returns
-------
None
"""
if self.current_op:
op_path = fsutils.USER_DATA_PATH / self.current_op
logger.debug("op_path: %s", str(op_path))
if op_path.is_dir() is False:
logger.debug("Creating Op Directory: %s", str(op_path))
os.mkdir(str(op_path))
if op_path.is_dir():
source_path = fsutils.APP_DATA_PATH / "phonetics"
logger.debug("source_path: %s", str(source_path))
for child in source_path.iterdir():
destination_file = op_path / child.name
if destination_file.is_file() is False:
logger.debug("Destination: %s", str(destination_file))
destination_file.write_bytes(child.read_bytes())
def poll_radio(self, the_dict: dict) -> None:
"""
Gets called by thread worker radio.py
Passing in a dictionary object with the
vfo freq, mode, bandwidth, and online state of the radio.
"""
# This section has nothing to do with polling the radio
# It's here because it gets called often enough to be useful.
if self.auto_cq is True:
now = datetime.datetime.now()
total_duration = self.auto_cq_time - self.auto_cq_then
elapsed_duration = now - self.auto_cq_then
if total_duration.total_seconds() > 0:
percentage_complete = int(
(elapsed_duration.total_seconds() / total_duration.total_seconds())
* 100
)
percentage_complete = min(100, percentage_complete)
self.cwprogressBar.setValue(100 - percentage_complete)
if now > self.auto_cq_time:
self.auto_cq_then = now
self.auto_cq_time = now + datetime.timedelta(
milliseconds=self.auto_cq_delay
)
self.process_function_key(self.F1)
if now > self.server_seen:
self.server_icon.setPixmap(self.redserver)
# The following pertains to radio polling.
logger.debug(f"{the_dict=}")
info_dirty = False
vfo = the_dict.get("vfoa", "")
mode = the_dict.get("mode", "")
bw = the_dict.get("bw", "")
if bw == "NONE":
bw = "0"
online = the_dict.get("online", False)
if self.rig_control.interface == "fake":
self.set_radio_icon(0)
elif online is False:
self.set_radio_icon(1)
else:
self.set_radio_icon(2)
if vfo == "":
return
if self.radio_state.get("vfoa") != vfo:
info_dirty = True
self.radio_state["vfoa"] = vfo
if self.pref.get("sandpqsy") is True and self.radioButton_sp.isChecked():
if max(int(vfo), self.sandpfreq) - min(int(vfo), self.sandpfreq) > 500:
self.clearinputs()
band = getband(str(vfo))
self.radio_state["band"] = band
self.contact["Band"] = get_logged_band(str(vfo))
self.set_band_indicator(band)
if self.radio_state.get("mode") != mode:
info_dirty = True
if "set_freq:" not in mode and not mode.isnumeric():
self.radio_state["mode"] = mode
if self.radio_state.get("bw") != bw:
info_dirty = True
self.radio_state["bw"] = bw
if mode in ("CW", "CW-U", "CW-L", "CWR"):
self.setmode(mode)
if mode in ("LSB", "USB", "FM", "AM"):
self.setmode("SSB")
if mode in (
"RTTY",
"RTTY-R",
"LSB-D",
"USB-D",
"AM-D",
"FM-D",
"DIGI-U",
"DIGI-L",
"DIG",
"RTTYR",
"PKTLSB",
"PKTUSB",
"FSK",
"PKT",
):
self.setmode("RTTY")
if self.bandmap_window:
cmd = {}
cmd["cmd"] = "RADIO_STATE"
cmd["band"] = band
cmd["vfoa"] = vfo
cmd["mode"] = mode
cmd["bw"] = bw
self.bandmap_window.msg_from_main(cmd)
if info_dirty:
try:
logger.debug("VFO: %s MODE: %s BW: %s", vfo, mode, bw)
self.set_window_title()
# cmd = {}
# cmd["cmd"] = "RADIO_STATE"
# cmd["band"] = band
# cmd["vfoa"] = vfo
# cmd["mode"] = mode
# cmd["bw"] = bw
# if self.bandmap_window:
# self.bandmap_window.msg_from_main(cmd)
if self.n1mm:
self.n1mm.radio_info["Freq"] = vfo[:-1]
self.n1mm.radio_info["TXFreq"] = vfo[:-1]
self.n1mm.radio_info["Mode"] = mode
self.n1mm.radio_info["OpCall"] = self.current_op
self.n1mm.radio_info["IsRunning"] = str(
self.pref.get("run_state", False)
)
if self.n1mm.send_radio_packets:
self.n1mm.send_radio()
if self.pref.get("useserver", False) is True:
cmd = {}
cmd["cmd"] = "STATION_STATE"
cmd["Band"] = band
cmd["Mode"] = mode
cmd["NetBiosName"] = socket.gethostname()
cmd["Operator"] = self.current_op
try:
self.server_channel.send_as_json(cmd)
except OSError as err:
logging.warning("%s", err)
except TypeError as err:
logger.debug(f"{err=} {vfo=} {the_dict=}")
def get_macro_filename(self) -> str:
"""
Have not1mm check in USER_DATA_PATH for the existence of a folder with the contests name.
If it exists, check to see if a cw/ssb/rtty macro files exists within it and load them before
falling back to the default ones.
If user selects menu option to edit the current macro file, make the previous checks, if the
specific one does not exist, copy the default to the contest directory and edit that copy.
"""
if self.radio_state.get("mode") in ("CW", "CW-U", "CW-L", "CW-R", "CWR"):
macro_file = "cwmacros.txt"
elif self.radio_state.get("mode") in (
"RTTY",
"RTTY-R",
"LSB-D",
"USB-D",
"AM-D",
"FM-D",
"DIGI-U",
"DIGI-L",
"RTTYR",
"PKTLSB",
"PKTUSB",
"FSK",
):
macro_file = "rttymacros.txt"
else:
macro_file = "ssbmacros.txt"
try:
if not (fsutils.USER_DATA_PATH / self.contest.name).exists():
os.mkdir(fsutils.USER_DATA_PATH / self.contest.name)
except AttributeError:
return ""
if not (fsutils.USER_DATA_PATH / macro_file).exists():
try:
copyfile(
fsutils.APP_DATA_PATH / macro_file,
fsutils.USER_DATA_PATH / macro_file,
)
except IOError as err:
logger.critical(f"Error {err} copying macro file.")
if not (fsutils.USER_DATA_PATH / self.contest.name / macro_file).exists():
try:
copyfile(
fsutils.USER_DATA_PATH / macro_file,
fsutils.USER_DATA_PATH / self.contest.name / macro_file,
)
except IOError as err:
logger.critical(f"Error {err} copying macro file.")
return fsutils.USER_DATA_PATH / self.contest.name / macro_file
def edit_macros(self) -> None:
"""
Calls the default text editor to edit the CW macro file.
Parameters
----------
None
Returns
-------
None
"""
macro_file = self.get_macro_filename()
try:
fsutils.openFileWithOS(macro_file)
except FileNotFoundError | PermissionError | OSError as err:
logger.critical(f"Could not open file {macro_file} {err}")
self.read_macros()
def read_macros(self) -> None:
"""
Reads in the CW macros, firsts it checks to see if the file exists. If it does not,
and this has been packaged with pyinstaller it will copy the default file from the
temp directory this is running from... In theory.
"""
macro_file = self.get_macro_filename()
try:
with open(macro_file, "r", encoding="utf-8") as file_descriptor:
for line in file_descriptor:
line = line.strip()
if not line:
continue
if line.startswith("#"):
continue
mode, fkey, buttonname, cwtext = line.split("|")
if mode.strip().upper() == "R" and self.pref.get("run_state"):
self.fkeys[fkey.strip()] = (buttonname.strip(), cwtext.strip())
if mode.strip().upper() != "R" and not self.pref.get("run_state"):
self.fkeys[fkey.strip()] = (buttonname.strip(), cwtext.strip())
except (IOError, ValueError) as err:
logger.info("read_cw_macros: %s", err)
keys = self.fkeys.keys()
if "F1" in keys:
self.F1.setText(f"F1: {self.fkeys['F1'][0]}")
self.F1.setToolTip(self.fkeys["F1"][1])
if "F2" in keys:
self.F2.setText(f"F2: {self.fkeys['F2'][0]}")
self.F2.setToolTip(self.fkeys["F2"][1])
if "F3" in keys:
self.F3.setText(f"F3: {self.fkeys['F3'][0]}")
self.F3.setToolTip(self.fkeys["F3"][1])
if "F4" in keys:
self.F4.setText(f"F4: {self.fkeys['F4'][0]}")
self.F4.setToolTip(self.fkeys["F4"][1])
if "F5" in keys:
self.F5.setText(f"F5: {self.fkeys['F5'][0]}")
self.F5.setToolTip(self.fkeys["F5"][1])
if "F6" in keys:
self.F6.setText(f"F6: {self.fkeys['F6'][0]}")
self.F6.setToolTip(self.fkeys["F6"][1])
if "F7" in keys:
self.F7.setText(f"F7: {self.fkeys['F7'][0]}")
self.F7.setToolTip(self.fkeys["F7"][1])
if "F8" in keys:
self.F8.setText(f"F8: {self.fkeys['F8'][0]}")
self.F8.setToolTip(self.fkeys["F8"][1])
if "F9" in keys:
self.F9.setText(f"F9: {self.fkeys['F9'][0]}")
self.F9.setToolTip(self.fkeys["F9"][1])
if "F10" in keys:
self.F10.setText(f"F10: {self.fkeys['F10'][0]}")
self.F10.setToolTip(self.fkeys["F10"][1])
if "F11" in keys:
self.F11.setText(f"F11: {self.fkeys['F11'][0]}")
self.F11.setToolTip(self.fkeys["F11"][1])
if "F12" in keys:
self.F12.setText(f"F12: {self.fkeys['F12'][0]}")
self.F12.setToolTip(self.fkeys["F12"][1])
def generate_adif(self) -> None:
"""
Calls the contest ADIF file generator.
Parameters
----------
None
Returns
-------
None
"""
# https://www.adif.org/315/ADIF_315.htm
logger.debug("******ADIF*****")
self.contest.adif(self)
def generate_edi(self) -> None:
"""
Calls the contest EDI file generator.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("******EDI*****")
if hasattr(self.contest, "edi"):
self.contest.edi(self)
def generate_cabrillo(self, file_encoding: str) -> None:
"""
Calls the contest Cabrillo file generator. Maybe.
Parameters
----------
None
Returns
-------
None
"""
logger.debug("******Cabrillo*****")
self.contest.cabrillo(self, file_encoding)
def import_adif(self) -> None:
"""
Calls the contest ADIF file importer.
Parameters
----------
None
Returns
-------
None
"""
# https://www.adif.org/315/ADIF_315.htm
logger.debug("******ADIF IMPORT*****")
self.contest.imp_adif(self)
def load_fonts_from_dir(self, directory: str) -> str:
"""
Well it loads fonts from a directory...
Parameters
----------
directory : str
The directory to load fonts from.
Returns
-------
set
A set of font families installed in the directory.
"""
font_families = set()
for _fi in QDir(directory).entryInfoList(["*.ttf", "*.woff", "*.woff2"]):
_id = QFontDatabase.addApplicationFont(_fi.absoluteFilePath())
font_families |= set(QFontDatabase.applicationFontFamilies(_id))
result = set((max(font_families, key=len),))
return list(result)[0]
def install_icons() -> None:
"""Install icons"""
if sys.platform == "linux":
os.system(
"xdg-icon-resource install --size 32 --context apps --mode user "
f"{fsutils.APP_DATA_PATH}/k6gte.not1mm-32.png k6gte-not1mm"
)
os.system(
"xdg-icon-resource install --size 64 --context apps --mode user "
f"{fsutils.APP_DATA_PATH}/k6gte.not1mm-64.png k6gte-not1mm"
)
os.system(
"xdg-icon-resource install --size 128 --context apps --mode user "
f"{fsutils.APP_DATA_PATH}/k6gte.not1mm-128.png k6gte-not1mm"
)
os.system(
f"xdg-desktop-menu install {fsutils.APP_DATA_PATH}/k6gte-not1mm.desktop"
)
QtGui.QGuiApplication.setDesktopFileName("k6gte-not1mm")
def doimp(modname: str) -> object:
"""
Imports a module.
Parameters
----------
modname : str
The name of the module to import.
Returns
-------
object
The module object.
"""
logger.debug("doimp: %s", modname)
return importlib.import_module(f"not1mm.plugins.{modname}")
def run() -> None:
"""
Main Entry
"""
install_icons()
splash.show()
# app.processEvents()
splash.showMessage(
"Starting Up",
alignment=Qt.AlignmentFlag.AlignBottom | Qt.AlignmentFlag.AlignCenter,
color=QColor(255, 255, 0),
)
QCoreApplication.processEvents()
# families = load_fonts_from_dir(os.fspath(fsutils.APP_DATA_PATH))
# logger.info(f"font families {families}")
window = MainWindow(splash)
window.callsign.setFocus()
splash.finish(window)
window.show()
logger.debug(
f"\nResolved OS file system paths:\nAPP_DATA_PATH {fsutils.APP_DATA_PATH}\nMODULE_PATH {fsutils.MODULE_PATH}\nUSER_DATA_PATH {fsutils.USER_DATA_PATH}\nCONFIG_PATH {fsutils.CONFIG_PATH}\nLOG_FILE {fsutils.LOG_FILE}"
)
sys.exit(app.exec())
DEBUG_ENABLED = False
if Path("./debug").exists() or os.environ.get("DEBUG", False):
DEBUG_ENABLED = True
logger = logging.getLogger("__main__")
logging.basicConfig(
level=logging.DEBUG if DEBUG_ENABLED else logging.CRITICAL,
format="[%(asctime)s] %(levelname)s %(name)s - %(funcName)s Line %(lineno)d: %(message)s",
handlers=[
RotatingFileHandler(fsutils.LOG_FILE, maxBytes=10490000, backupCount=20),
logging.StreamHandler(),
],
)
logging.getLogger("PyQt6.uic.uiparser").setLevel("INFO")
logging.getLogger("PyQt6.uic.properties").setLevel("INFO")
app = QtWidgets.QApplication(sys.argv)
pixmap = QPixmap(f"{os.fspath(fsutils.APP_DATA_PATH)}/splash.png")
splash = QSplashScreen(pixmap)
if __name__ == "__main__":
run()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1778213070.0
not1mm-26.5.8/not1mm/bandmap.py 0000755 0001750 0001750 00000105515 15177260316 016104 0 ustar 00mbridak mbridak #!/usr/bin/env python3
"""
not1mm Contest logger
Email: michael.bridak@gmail.com
GPL V3
Class: BandMapWindow
Purpose: Onscreen widget to show realtime spots from an AR cluster.
"""
# pylint: disable=unused-import, c-extension-no-member, no-member, invalid-name, too-many-lines
# pylint: disable=logging-fstring-interpolation, line-too-long, no-name-in-module
import logging
import os
import platform
import re
import sqlite3
from datetime import datetime, timezone
from decimal import Decimal
from json import loads
from PyQt6 import QtCore, QtGui, QtWidgets, uic, QtNetwork
from PyQt6.QtGui import QColorConstants, QFont, QColor
from PyQt6.QtWidgets import QDockWidget, QStyle
from PyQt6.QtCore import Qt, pyqtSignal
import not1mm.fsutils as fsutils
# from not1mm.lib.multicast import Multicast
logger = logging.getLogger(__name__)
PIXELSPERSTEP = 10
UPDATE_INTERVAL = 2000
CLEAR_FREQ = 0.1 # 100 Hz
class Band:
"""the band"""
bands = {
"160m": (1800, 2000, 1.8),
"80m": (3500, 4000, 3.5),
"60m": (5102, 5407, 5.1),
"40m": (7000, 7300, 7.0),
"30m": (10100, 10150, 10.0),
"20m": (14000, 14350, 14.0),
"17m": (18068, 18168, 18.0),
"15m": (21000, 21450, 21.0),
"12m": (24890, 24990, 24.0),
"10m": (28000, 29700, 28.0),
"6m": (50000, 54000, 50.0),
"4m": (70000, 71000, 70.0),
"2m": (144_000, 148_000, 144.0),
"70cm": (420_000, 450_000, 432.0),
"33cm": (902_000, 928_000, 932.0),
"23cm": (1240_000, 1300_000, 1232.0),
} # fmt: skip
def __init__(self, band: str) -> None:
self.start, self.end, self.altname = self.bands.get(band, (0.0, 1.0, 0.0))
self.name = band
def new_from_freq(freq: float) -> (float, float):
"""Find band matching a frequency."""
for band, edges in Band.bands.items():
if edges[0] <= freq <= edges[1]:
return Band(band)
return Band("unknown")
class Database:
"""
An in memory Database class to hold spots.
"""
def __init__(self) -> None:
self.db = sqlite3.connect(":memory:")
self.db.row_factory = self.row_factory
self.cursor = self.db.cursor()
sql_command = (
"create table spots ("
"callsign VARCHAR(15) NOT NULL, "
"ts DATETIME NOT NULL, "
"freq DOUBLE NOT NULL, " # in kHz
"mode VARCHAR(6), "
"spotter VARCHAR(15) NOT NULL, "
"comment VARCHAR(45));"
)
self.cursor.execute(sql_command)
self.cursor.execute("CREATE INDEX spot_call_index ON spots (callsign);")
self.cursor.execute("CREATE INDEX spot_freq_index ON spots (freq);")
self.cursor.execute("CREATE INDEX spot_ts_index ON spots (ts);")
self.db.commit()
@staticmethod
def row_factory(cursor, row):
"""
cursor.description:
(name, type_code, display_size,
internal_size, precision, scale, null_ok)
row: (value, value, ...)
"""
return {
col[0]: row[idx]
for idx, col in enumerate(
cursor.description,
)
}
def get_like_calls(self, call: str) -> dict:
"""
Returns spots where the spotted callsigns contain the supplied string.
Parameters
----------
call : str
The callsign to search for.
Returns
-------
a dict like:
{'K5TUX': [14.0, 21.0], 'N2CQR': [14.0], 'NE4RD': [14.0]}
"""
try:
self.cursor.execute(
f"select distinct callsign from spots where callsign like '%{call}%' ORDER by callsign ASC;"
)
result = self.cursor.fetchall()
return result
except sqlite3.OperationalError as exception:
logger.debug("%s", exception)
return {}
def addspot(self, spot: dict, clear_freq=False) -> None:
"""
Add spot to database, replacing any previous spots with the same call
on the same band.
Parameters
----------
spot: Dict
A dict of the form: {'ts': datetime, 'callsign': str, 'freq': float,
'band': str,'mode': str,'spotter': str, 'comment': str}
clear_freq: bool
If True, delete any previous spots around this frequency.
Returns
-------
Nothing.
"""
if "band" in spot:
band = Band(spot.get("band"))
else:
band = Band.new_from_freq(spot.get("freq"))
try:
delete_call_q = (
"delete from spots where callsign = ? and freq between ? and ?;"
)
self.cursor.execute(
delete_call_q, (spot.get("callsign"), band.start, band.end)
)
if clear_freq:
clear_freq_q = "delete from spots where freq between ? and ?;"
self.cursor.execute(
clear_freq_q,
(spot.get("freq") - CLEAR_FREQ, spot.get("freq") + CLEAR_FREQ),
)
self.cursor.execute(
"INSERT INTO spots(callsign, ts, freq, mode, spotter, comment) VALUES(?, ?, ?, ?, ?, ?)",
(
spot["callsign"],
spot.get("ts", datetime.now(timezone.utc).replace(second=0, microsecond=0, tzinfo=None)),
spot["freq"],
spot.get("mode", None),
spot.get("spotter", platform.node()),
spot.get("comment", None),
),
)
self.db.commit()
except sqlite3.IntegrityError:
...
def getspots(self) -> list:
"""
Return a list of spots, sorted by the ascending frequency of the spot.
Parameters
----------
None
Returns
-------
a list of dicts.
"""
try:
self.cursor.execute("select * from spots order by freq ASC;")
return self.cursor.fetchall()
except sqlite3.OperationalError:
return ()
def getspotsinband(self, start: float, end: float) -> list:
"""
Returns spots in a list of dicts where the spotted frequency
is in the range defined, in ascending order.
Parameters
----------
start : float
The start frequency.
end : float
The end frequency.
Returns
-------
A list of dicts.
"""
self.cursor.execute(
"select * from spots where freq >= ? and freq <= ? order by freq ASC;",
(start, end),
)
return self.cursor.fetchall()
def get_next_spot(self, current: float, limit: float) -> dict:
"""
Return a list of dict where freq range is defined by current and limit.
The list is sorted by the ascending frequency of the spot.
Parameters
----------
current : float
The current frequency.
limit : float
The limit frequency.
Returns
-------
A dict of the spot.
"""
self.cursor.execute(
"select * from spots where freq > ? and freq <= ? order by freq ASC;",
(current, limit),
)
return self.cursor.fetchone()
def get_matching_spot(self, dx: str, start: float, end: float) -> dict:
"""
Return the first spot matching supplied dx partial callsign.
Parameters
----------
dx : str
The dx partial callsign.
start : float
The start frequency.
end : float
The end frequency.
Returns
-------
A dict of the spot.
"""
self.cursor.execute(
"select * from spots where freq >= ? and freq <= ? and callsign like ?;",
(start, end, f"%{dx}%"),
)
return self.cursor.fetchone()
def get_prev_spot(self, current: float, limit: float) -> dict:
"""
Return a list of dict where freq range is defined in descending order.
Parameters
----------
current : float
The current frequency.
limit : float
The limit frequency.
Returns
-------
A list of dicts.
"""
self.cursor.execute(
"select * from spots where freq < ? and freq >= ? order by freq DESC;",
(current, limit),
)
return self.cursor.fetchone()
def delete_spot(self, call: str, freq: float) -> None:
"""
Delete a spot identified by call and frequency.
"""
self.cursor.execute(
"delete from spots where callsign = ? and freq = ?",
(call, freq))
self.db.commit()
def delete_spots(self, minutes: int) -> None:
"""
Delete spots older than the specified number of minutes.
Parameters
----------
minutes : int
The number of minutes to delete.
Returns
-------
None
"""
self.cursor.execute(
"delete from spots where ts < datetime('now', ?);",
(f"-{minutes} minutes",),
)
def delete_marks(self) -> None:
"""Delete marked spots."""
self.cursor.execute("delete from spots where ts > datetime('now');")
class BandMapScene(QtWidgets.QGraphicsScene):
"""
QGraphicsScene class with custom context menu hook.
"""
def __init__(self, parent=None):
super().__init__(parent)
self.parent = parent
def contextMenuEvent(self, event):
item = self.itemAt(event.scenePos(), QtGui.QTransform())
if item:
callsign = item.property("callsign")
freq = item.property("freq")
comment = item.toolTip()
menu = QtWidgets.QMenu()
menu.addAction("Confirm", lambda: self.parent.spots.addspot({
"callsign": callsign,
"freq": freq,
"comment": comment,
}, True))
if "MARKED" in comment:
menu.addAction("Unmark", lambda: self.parent.spots.addspot({
"callsign": callsign,
"freq": freq,
"comment": comment.replace("MARKED", ""),
}, True))
else:
menu.addAction("Mark", lambda: self.parent.spots.addspot({
"callsign": callsign,
"freq": freq,
"comment": comment + " MARKED",
}, True))
menu.addAction("Delete", lambda: self.parent.spots.delete_spot(callsign, freq))
menu.exec(event.screenPos())
else:
super().contextMenuEvent(event)
class BandMapWindow(QDockWidget):
"""The BandMapWindow class."""
zoom = 5
currentBand = Band("20m")
txMark = []
rxMark = []
rx_freq = None
tx_freq = None
something = None
lineitemlist = []
textItemList = []
connected = False
bandwidth = 0
bandwidth_mark = []
worked_list = {}
multicast_interface = None
text_color = QColor(45, 45, 45)
worked_color = QColor(128, 128, 128)
cluster_expire = pyqtSignal(str)
message = pyqtSignal(dict)
date_pattern = r"^\d{2}-[A-Za-z]{3}-\d{4}$"
wwv_pattern = (
r"(\d{2}-\w{3}-\d{4})\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(.*?)\s+<(\w+)>"
)
bandmapwindow_closed = pyqtSignal()
def __init__(self, action):
super().__init__()
self.action = action
self.active = False
self._udpwatch = None
uic.loadUi(fsutils.APP_DATA_PATH / "bandmap.ui", self)
# self.thefont = QFont()
# self.thefont.setFamily("JetBrains Mono")
self.thefont = QFont("JetBrains Mono", 10)
self.settings = self.get_settings()
self.clear_spot_olderSpinBox.setValue(
int(self.settings.get("cluster_expire", 1))
)
self.agetime = self.clear_spot_olderSpinBox.value()
self.clear_spot_olderSpinBox.valueChanged.connect(self.spot_aging_changed)
self.clearButton.clicked.connect(self.clear_spots)
pixmapi = QStyle.StandardPixmap.SP_TrashIcon
icon = self.style().standardIcon(pixmapi)
self.clearButton.setIcon(icon)
self.clearmarkedButton.clicked.connect(self.clear_marked)
self.clearmarkedButton.setIcon(icon)
self.zoominButton.clicked.connect(self.dec_zoom)
self.zoomoutButton.clicked.connect(self.inc_zoom)
self.connectButton.clicked.connect(self.connect)
self.spots = Database()
# self.font = QFont("JetBrains Mono ExtraLight", 10)
self.socket = QtNetwork.QTcpSocket()
self.socket.readyRead.connect(self.receive)
self.socket.connected.connect(self.maybeconnected)
self.socket.disconnected.connect(self.disconnected)
self.socket.errorOccurred.connect(self.socket_error)
self.bandmap_scene = BandMapScene(self)
self.bandmap_scene.setFont(self.thefont)
self.bandmap_scene.clear()
self.bandmap_scene.setFocusOnTouch(False)
self.bandmap_scene.selectionChanged.connect(self.spot_clicked)
self.freq = 0.0
self.keepRXCenter = False
self.update_timer = QtCore.QTimer()
self.update_timer.timeout.connect(self.update_station_timer)
self.update_timer.start(UPDATE_INTERVAL)
self.setDarkMode()
self.update()
self.request_workedlist()
self.request_contest()
def setActive(self, mode: bool):
self.active = bool(mode)
self.request_workedlist()
def get_settings(self) -> dict:
"""Get the settings."""
if os.path.exists(fsutils.CONFIG_FILE):
with open(fsutils.CONFIG_FILE, "rt", encoding="utf-8") as file_descriptor:
return loads(file_descriptor.read())
def msg_from_main(self, packet):
""""""
if self.active is False or not self.isVisible():
return
if packet.get("cmd", "") == "RADIO_STATE":
target_band_name = packet.get("band", "")
if len(target_band_name):
if target_band_name[-1:] == "m":
self.set_band(target_band_name, False)
else:
self.set_band(packet.get("band") + "m", False)
try:
if self.rx_freq != float(packet.get("vfoa")) / 1000:
self.rx_freq = float(packet.get("vfoa")) / 1000
self.tx_freq = self.rx_freq
self.center_on_rxfreq()
except ValueError:
print(f"vfo value error {packet.get('vfoa')}")
logger.debug(f"vfo value error {packet.get('vfoa')}")
return
bw_returned = packet.get("bw", "0")
if not bw_returned.isdigit():
bw_returned = "0"
self.bandwidth = int(bw_returned)
step, _ = self.determine_step_digits()
self.drawTXRXMarks(step)
return
if packet.get("cmd", "") == "NEXTSPOT" and self.rx_freq:
spot = self.spots.get_next_spot(self.rx_freq + 0.001, self.currentBand.end)
if spot:
cmd = {}
cmd["cmd"] = "TUNE"
cmd["freq"] = spot.get("freq", self.rx_freq)
cmd["spot"] = spot.get("callsign", "")
self.message.emit(cmd)
return
if packet.get("cmd", "") == "PREVSPOT" and self.rx_freq:
spot = self.spots.get_prev_spot(
self.rx_freq - 0.001, self.currentBand.start
)
if spot:
cmd = {}
cmd["cmd"] = "TUNE"
cmd["freq"] = spot.get("freq", self.rx_freq)
cmd["spot"] = spot.get("callsign", "")
self.message.emit(cmd)
return
if packet.get("cmd", "") == "SPOTDX":
dx = packet.get("dx", "")
freq = packet.get("freq", 0.0)
spotdx = f"dx {dx} {freq}"
self.send_command(spotdx)
return
if packet.get("cmd", "") == "MARKDX":
dx = packet.get("dx", "")
freq = packet.get("freq", 0.0)
the_UTC_time = datetime.now(timezone.utc).isoformat(" ")[:19].split()[1]
comment = packet.get("comment", "")
spot = {
"ts": "2099-01-01 " + the_UTC_time,
"callsign": dx,
"freq": freq,
"band": self.currentBand.name,
"mode": "DX",
"spotter": platform.node(),
"comment": comment,
}
self.spots.addspot(spot, clear_freq=True)
self.update_stations()
return
if packet.get("cmd", "") == "FINDDX":
dx = packet.get("dx", "")
spot = self.spots.get_matching_spot(
dx, self.currentBand.start, self.currentBand.end
)
if spot:
cmd = {}
cmd["cmd"] = "TUNE"
cmd["freq"] = spot.get("freq", self.rx_freq)
cmd["spot"] = spot.get("callsign", "")
self.message.emit(cmd)
return
if packet.get("cmd", "") == "WORKED":
self.worked_list = packet.get("worked", {})
logger.debug("%s", f"{self.worked_list}")
self.update_stations()
return
if packet.get("cmd", "") == "CALLCHANGED":
call = packet.get("call", "")
if call:
result = self.spots.get_like_calls(call)
if result:
cmd = {}
cmd["cmd"] = "CHECKSPOTS"
cmd["spots"] = result
self.message.emit(cmd)
return
cmd = {}
cmd["cmd"] = "CHECKSPOTS"
cmd["spots"] = []
self.message.emit(cmd)
return
if packet.get("cmd", "") == "CONTESTSTATUS":
if not self.callsignField.text():
self.callsignField.setText(packet.get("operator", "").upper())
return
if packet.get("cmd", "") == "DARKMODE":
self.setDarkMode()
def is_it_dark(self) -> bool:
"""Returns if the DE has a dark theme active."""
hints = QtGui.QGuiApplication.styleHints()
scheme = hints.colorScheme()
return scheme == Qt.ColorScheme.Dark
def setDarkMode(self):
"""Set dark mode"""
setdarkmode = self.is_it_dark()
if setdarkmode is True:
self.text_color = QColorConstants.White
self.worked_color = QColor(108, 108, 108)
self.update()
else:
self.text_color = QColorConstants.Black
self.worked_color = QColor(178, 178, 178)
self.update()
def connect(self):
"""Connect to the cluster."""
if not self.callsignField.text():
self.callsignField.setFocus()
return
if self.connected is True:
self.close_cluster()
return
self.settings = self.get_settings()
server = self.settings.get("cluster_server", "dxc.nc7j.com")
port = self.settings.get("cluster_port", 7373)
logger.info(f"connecting to dx cluster {server} {port}")
self.socket.connectToHost(server, port)
self.connectButton.setText("Connecting")
self.connected = True
def spot_clicked(self):
"""dunno"""
items = self.bandmap_scene.selectedItems()
for item in items:
if item:
cmd = {}
cmd["cmd"] = "TUNE"
cmd["freq"] = items[0].property("freq")
cmd["spot"] = items[0].toPlainText().split()[0]
self.message.emit(cmd)
def request_workedlist(self):
"""Request worked call list from logger"""
cmd = {}
cmd["cmd"] = "GETWORKEDLIST"
self.message.emit(cmd)
def request_contest(self):
"""Request active contest from logger"""
cmd = {}
cmd["cmd"] = "GETCONTESTSTATUS"
self.message.emit(cmd)
def update_station_timer(self):
"""doc"""
self.update_stations()
def update(self):
"""doc"""
try:
self.update_timer.setInterval(UPDATE_INTERVAL)
except AttributeError:
...
# if self.active is False:
# return
self.clear_all_callsign_from_scene()
self.clear_freq_mark(self.rxMark)
self.clear_freq_mark(self.txMark)
self.clear_freq_mark(self.bandwidth_mark)
self.bandmap_scene.clear()
# self.bandmap_scene.setFont(self.font)
self.bandmap_scene.setFont(self.thefont)
step, _digits = self.determine_step_digits()
steps = int(round((self.currentBand.end - self.currentBand.start) / step)) + 1
self.graphicsView.setFixedSize(330, steps * PIXELSPERSTEP + 30)
self.graphicsView.setScene(self.bandmap_scene)
# self.graphicsView.setFont(self.font)
self.graphicsView.setFont(self.thefont)
for i in range(steps): # Draw tickmarks
length = 10
if i % 5 == 0:
length = 15
self.bandmap_scene.addLine(
10,
i * PIXELSPERSTEP,
length + 10,
i * PIXELSPERSTEP,
QtGui.QPen(self.text_color),
)
if i % 5 == 0: # Add Frequency
freq = self.currentBand.start + step * i
# text = f"{freq:.3f}"
text = "{1:.{0}f}".format(_digits, freq)
self.something = self.bandmap_scene.addText(text)
self.something.setFont(self.thefont)
self.something.setDefaultTextColor(self.text_color)
self.something.setPos(
-(self.something.boundingRect().width()) + 10,
i * PIXELSPERSTEP - (self.something.boundingRect().height() / 2),
)
freq = self.currentBand.end + step * steps
endFreqDigits = f"{freq:.1f}"
self.bandmap_scene.setSceneRect(
160 - (len(endFreqDigits) * PIXELSPERSTEP), 0, 0, steps * PIXELSPERSTEP + 20
)
self.drawTXRXMarks(step)
self.update_stations()
def inc_zoom(self):
"""doc"""
self.zoom += 1
self.zoom = min(self.zoom, 7)
self.update()
self.center_on_rxfreq()
def dec_zoom(self):
"""doc"""
self.zoom -= 1
self.zoom = max(self.zoom, 0)
self.update()
self.center_on_rxfreq()
def drawTXRXMarks(self, step):
"""doc"""
if self.rx_freq:
self.clear_freq_mark(self.bandwidth_mark)
self.clear_freq_mark(self.rxMark)
self.draw_bandwidth(
self.rx_freq, step, QColor(30, 30, 180, 180), self.bandwidth_mark
)
self.drawfreqmark(self.rx_freq, step, QColor(30, 180, 30, 180), self.rxMark)
def Freq2ScenePos(self, freq: float):
"""doc"""
if not freq or freq < self.currentBand.start or freq > self.currentBand.end:
return QtCore.QPointF()
step, _digits = self.determine_step_digits()
ret = QtCore.QPointF(
0,
(
(Decimal(str(freq)) - Decimal(str(self.currentBand.start)))
/ Decimal(str(step))
)
* PIXELSPERSTEP,
)
return ret
def center_on_rxfreq(self):
"""doc"""
freq_pos = self.Freq2ScenePos(self.rx_freq).y()
self.scrollArea.verticalScrollBar().setValue(
int(freq_pos - (self.height() / 2) + 80)
)
def drawfreqmark(self, freq, _step, color, currentPolygon) -> None:
"""doc"""
self.clear_freq_mark(currentPolygon)
# do not show the freq mark if it is outside the bandmap
if freq < self.currentBand.start or freq > self.currentBand.end:
return
Yposition = self.Freq2ScenePos(freq).y()
poly = QtGui.QPolygonF()
poly.append(QtCore.QPointF(21, Yposition))
poly.append(QtCore.QPointF(10, Yposition - 7))
poly.append(QtCore.QPointF(10, Yposition + 7))
pen = QtGui.QPen()
brush = QtGui.QBrush(color)
currentPolygon.append(self.bandmap_scene.addPolygon(poly, pen, brush))
def draw_bandwidth(self, freq, _step, color, currentPolygon) -> None:
"""bandwidth"""
logger.debug("%s", f"mark:{currentPolygon} f:{freq} b:{self.bandwidth}")
self.clear_freq_mark(currentPolygon)
if freq < self.currentBand.start or freq > self.currentBand.end:
return
if freq and self.bandwidth:
# color = QColor(30, 30, 180)
bw_start = Decimal(str(freq)) - ((Decimal(str(self.bandwidth)) / 2) / 1000)
bw_end = Decimal(str(freq)) + ((Decimal(str(self.bandwidth)) / 2) / 1000)
logger.debug("%s", f"s:{bw_start} e:{bw_end}")
Yposition_neg = self.Freq2ScenePos(bw_start).y()
Yposition_pos = self.Freq2ScenePos(bw_end).y()
poly = QtGui.QPolygonF()
poly.append(QtCore.QPointF(15, Yposition_neg))
poly.append(QtCore.QPointF(20, Yposition_neg))
poly.append(QtCore.QPointF(20, Yposition_pos))
poly.append(QtCore.QPointF(15, Yposition_pos))
pen = QtGui.QPen()
brush = QtGui.QBrush(color)
currentPolygon.append(self.bandmap_scene.addPolygon(poly, pen, brush))
def update_stations(self):
"""doc"""
self.update_timer.setInterval(UPDATE_INTERVAL)
if self.active is False or not self.isVisible():
return
self.clear_all_callsign_from_scene()
self.spot_aging()
step, _digits = self.determine_step_digits()
result = self.spots.getspotsinband(self.currentBand.start, self.currentBand.end)
logger.debug(
f"{len(result)} spots in range {self.currentBand.start} - {self.currentBand.end}"
)
entity = ""
if result:
# ⌾ ⦿ 🗼 ⛯ ⊕ ⊞ ⁙ ⁘ ⁕ ⌖ Ⓟ ✦ 🄿 🄿 Ⓢ 🅂 🏔
min_y = 0.0
for items in result:
flag = " @"
if "CW" in items.get("comment"):
flag = " ○"
if "NCDXF B" in items.get("comment"):
flag = " 🗼"
if "BCN " in items.get("comment"):
flag = " 🗼"
if "FT8" in items.get("comment"):
flag = " ⦿"
if "FT4" in items.get("comment"):
flag = " ⦿"
if "RTTY" in items.get("comment"):
flag = " ⌾"
if "POTA" in items.get("comment"):
flag += "[P]"
if "SOTA" in items.get("comment"):
flag += "[S]"
pen_color = self.text_color
if "MARKED" in items.get("comment"):
setdarkmode = self.is_it_dark()
if setdarkmode is True:
pen_color = QColor(254, 194, 17)
else:
pen_color = QColor(0, 160, 0)
if items.get("callsign") in self.worked_list:
call_bandlist = self.worked_list.get(items.get("callsign"))
if self.currentBand.altname in call_bandlist:
pen_color = self.worked_color
freq_y = (
(items.get("freq") - self.currentBand.start) / step
) * PIXELSPERSTEP
text_y = max(min_y + 5, freq_y)
self.lineitemlist.append(
self.bandmap_scene.addLine(
22, freq_y, 55, text_y, QtGui.QPen(pen_color)
)
)
text = self.bandmap_scene.addText(
items.get("callsign")
+ flag
+ entity
+ " "
+ items.get("ts").split()[1][:-3]
)
text.setFont(self.thefont)
text.document().setDocumentMargin(0)
text.setPos(60, text_y - (text.boundingRect().height() / 2))
text.setFlags(
QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsFocusable
| QtWidgets.QGraphicsItem.GraphicsItemFlag.ItemIsSelectable
| text.flags()
)
text.setProperty("callsign", items.get("callsign"))
text.setProperty("freq", items.get("freq"))
text.setToolTip(items.get("comment"))
text.setDefaultTextColor(pen_color)
min_y = text_y + text.boundingRect().height() / 2
self.textItemList.append(text)
def determine_step_digits(self):
"""doc"""
return_zoom = {
0: (0.04, 1),
1: (0.1, 1),
2: (0.2, 0),
3: (0.4, 0),
4: (1, 0),
5: (2, 0),
6: (4, 0),
7: (10, 0),
}
step, digits = return_zoom.get(self.zoom, (0.1, 1))
if self.currentBand.start >= 28.0 and self.currentBand.start < 420.0:
step = step * 10
return (step, digits)
if self.currentBand.start >= 420.0 and self.currentBand.start < 2300.0:
step = step * 100
return (step, digits)
def set_band(self, band: str, savePrevBandZoom: bool) -> None:
"""Change band being shown."""
logger.debug("%s", f"{band} {savePrevBandZoom}")
if band != self.currentBand.name:
if savePrevBandZoom:
self.saveCurrentZoom()
self.currentBand = Band(band)
self.update()
def spot_aging(self) -> None:
"""Delete spots older than age time."""
if self.agetime:
self.spots.delete_spots(self.agetime)
def clear_all_callsign_from_scene(self) -> None:
"""Remove callsigns from the scene."""
for items in self.textItemList:
self.bandmap_scene.removeItem(items)
self.textItemList.clear()
for items in self.lineitemlist:
self.bandmap_scene.removeItem(items)
self.lineitemlist.clear()
def clear_freq_mark(self, currentPolygon) -> None:
"""Remove frequency marks from the scene."""
if currentPolygon:
for mark in currentPolygon:
self.bandmap_scene.removeItem(mark)
currentPolygon.clear()
def receive(self) -> None:
"""Process waiting bytes"""
while self.socket.bytesAvailable():
data = self.socket.readLine(1000)
try:
data = str(data, "utf-8").strip()
except UnicodeDecodeError:
continue
if os.environ.get("SEND_CLUSTER", False) is not False:
print(f"{data}")
if (
"login:" in data.lower()
or "call:" in data.lower()
or "callsign:" in data.lower()
):
self.send_command(self.callsignField.text())
return
if "password:" in data.lower():
self.send_command(self.settings.get("cluster_password", ""))
return
if "BEACON" in data:
return
if "DX de" in data:
parts = data.split()
spotter = parts[2]
freq = parts[3]
dx = parts[4]
_time = parts[-1]
comment = " ".join(parts[5:-1])
spot = {}
spot["ts"] = datetime.now(timezone.utc).isoformat(" ")[:19]
spot["callsign"] = dx
spot["spotter"] = spotter
spot["comment"] = comment
logger.debug(f"{spot}")
try:
spot["freq"] = float(freq)
self.spots.addspot(spot)
except ValueError:
logger.debug(f"couldn't parse freq from datablock {data}")
return
if "HELLO" in data.upper():
self.connectButton.setText("Connected")
self.send_command(self.settings.get("cluster_filter", ""))
self.send_command("set dx extension Section")
self.send_command(
"set dx mode " + self.settings.get("cluster_mode", "OPEN")
)
self.send_command("sh wwv 1")
logger.debug(f"callsign login acknowledged {data}")
match = re.search(self.wwv_pattern, data)
if match:
cmd = {}
cmd["cmd"] = "SPACEWEATHER"
cmd["date"] = match.group(1)
cmd["hour"] = match.group(2)
cmd["sfi"] = match.group(3)
cmd["aindex"] = match.group(4)
cmd["kindex"] = match.group(5)
cmd["conditions"] = match.group(6).strip()
cmd["source"] = match.group(7)
self.message.emit(cmd)
def maybeconnected(self) -> None:
"""Update visual state of the connect button."""
self.connectButton.setText("Connecting")
def socket_error(self) -> None:
"""Oopsie"""
logger.warning("An Error occurred.")
def disconnected(self) -> None:
"""Called when socket is disconnected."""
self.connected = False
self.connectButton.setText("Closed")
def send_command(self, cmd: str) -> None:
"""Send a command to the cluster."""
cmd += "\r\n"
if os.environ.get("SEND_CLUSTER", False) is not False:
print(f"{cmd}")
tosend = bytes(cmd, encoding="ascii")
logger.debug("Command sent to the cluster")
if self.socket:
if self.socket.isOpen():
self.socket.write(tosend)
def clear_spots(self) -> None:
"""Delete all spots from the database."""
self.spots.delete_spots(0)
def clear_marked(self) -> None:
"""Delete all marked spots."""
self.spots.delete_marks()
def spot_aging_changed(self) -> None:
"""Called when spot aging spinbox is changed."""
self.agetime = self.clear_spot_olderSpinBox.value()
self.cluster_expire.emit(str(self.agetime))
def showContextMenu(self) -> None:
"""doc string for the linter"""
def close_cluster(self) -> None:
"""Close socket connection"""
if self.socket and self.socket.isOpen():
logger.info("Closing dx cluster connection")
self.socket.close()
self.connected = False
self.connectButton.setText("Closed")
def closeEvent(self, _event: QtGui.QCloseEvent) -> None:
"""Triggered when instance closes."""
self.close_cluster()
self.action.setChecked(False)
self.bandmapwindow_closed.emit()
_event.accept()
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1773247885.0
not1mm-26.5.8/not1mm/chat.py 0000644 0001750 0001750 00000006045 15154316615 015413 0 ustar 00mbridak mbridak import datetime
import logging
import os
# import sys
from PyQt6 import uic, QtGui
from PyQt6.QtWidgets import QDockWidget
from PyQt6.QtCore import pyqtSignal
import not1mm.fsutils as fsutils
from json import loads
from json.decoder import JSONDecodeError
logger = logging.getLogger(__name__)
# chat_history QTextBrowser
# chat_input QLineedit
class ChatWindow(QDockWidget):
"""The stats window. Shows something important."""
message = pyqtSignal(dict)
chatwindow_closed = pyqtSignal()
mycall = ""
poll_time = datetime.datetime.now() + datetime.timedelta(milliseconds=1000)
def __init__(self, action):
super().__init__()
self.action = action
self.active: bool = False
# self.load_pref()
uic.loadUi(fsutils.APP_DATA_PATH / "chat.ui", self)
self.chat_input.returnPressed.connect(self.send_chat)
def send_chat(self):
"""Sends UDP chat packet with text entered in chat_entry field."""
chat_string = self.chat_input.text()
packet = {"cmd": "CHAT"}
# packet["sender"] = self.preference.get("mycall", "")
packet["message"] = chat_string
self.message.emit(packet)
self.chat_input.setText("")
def display_chat(self, sender, body):
"""Displays the chat history."""
if self.mycall in body.upper():
self.chat_history.setTextColor(QtGui.QColor(245, 121, 0))
self.chat_history.insertPlainText(f"\n{sender}: {body}")
self.chat_history.setTextColor(QtGui.QColor(211, 215, 207))
self.chat_history.ensureCursorVisible()
def msg_from_main(self, packet):
""""""
if packet.get("cmd", "") == "CHAT":
# {"cmd": "CHAT", "sender": "N2CQR", "message": "I worked your mama on 80 meters."}
self.display_chat(packet.get("sender", ""), packet.get("message", ""))
return
if packet.get("cmd", "") == "CONTESTSTATUS":
self.mycall = packet.get("operator", "").upper()
return
def setActive(self, mode: bool) -> None:
self.active: bool = bool(mode)
def load_pref(self) -> None:
"""
Load preference file to get current db filename and sets the initial darkmode state.
Parameters
----------
None
Returns
-------
None
"""
try:
if os.path.exists(fsutils.CONFIG_FILE):
with open(
fsutils.CONFIG_FILE, "rt", encoding="utf-8"
) as file_descriptor:
self.pref = loads(file_descriptor.read())
logger.info(f"loaded config file from {fsutils.CONFIG_FILE}")
else:
self.pref["current_database"] = "ham.db"
except (IOError, JSONDecodeError) as exception:
logger.critical("Error: %s", exception)
def closeEvent(self, event) -> None:
self.action.setChecked(False)
self.chatwindow_closed.emit()
event.accept()
if __name__ == "__main__":
print("This is not a program.\nTry Again.")
././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1778213070.0
not1mm-26.5.8/not1mm/checkwindow.py 0000644 0001750 0001750 00000022637 15177260316 017007 0 ustar 00mbridak mbridak #!/usr/bin/env python3
"""
not1mm Contest logger
Email: michael.bridak@gmail.com
GPL V3
Class: CheckWindow
Purpose: Onscreen widget to show possible matches to callsigns entered in the main window.
"""
# pylint: disable=no-name-in-module, unused-import, no-member, invalid-name, c-extension-no-member
# pylint: disable=logging-fstring-interpolation, line-too-long
from dataclasses import dataclass
import logging
import os
import queue
from typing import Optional
from json import loads
from rapidfuzz.distance import Levenshtein
from PyQt6 import uic
from PyQt6.QtWidgets import QLabel, QVBoxLayout, QWidget, QDockWidget, QApplication
from PyQt6.QtGui import QMouseEvent
from PyQt6.QtCore import pyqtSignal
import not1mm.fsutils as fsutils
from not1mm.lib.database import DataBase
from not1mm.lib.super_check_partial import SCP
logger = logging.getLogger(__name__)
class CheckWindow(QDockWidget):
"""The check window. Shows list or probable stations."""
@dataclass
class BackgroundColors:
"""Background color data for the checkpartial call signs."""
character_remove_color: str
character_add_color: str
character_match_color: str
message = pyqtSignal(dict)
dbname = None
pref = {}
call = None
masterLayout: QVBoxLayout = None
dxcLayout: QVBoxLayout = None
qsoLayout: QVBoxLayout = None
background_colors_cache: Optional[BackgroundColors] = None
checkwindow_closed = pyqtSignal()
masterScrollWidget: QWidget = None
def __init__(self, action):
super().__init__()
self.action = action
self.active = False
self.load_pref()
self.dbname = fsutils.USER_DATA_PATH / self.pref.get(
"current_database", "ham.db"
)
self.database = DataBase(self.dbname, fsutils.APP_DATA_PATH)
self.database.current_contest = self.pref.get("contest", 0)
uic.loadUi(fsutils.APP_DATA_PATH / "checkwindow.ui", self)
self.mscp = SCP(fsutils.APP_DATA_PATH)
self._udpwatch = None
self.udp_fifo = queue.Queue()
def invalidate_background_colors_cache_on_mode_change():
self.background_colors_cache = None
QApplication.instance().styleHints().colorSchemeChanged.connect(
invalidate_background_colors_cache_on_mode_change
)
def msg_from_main(self, packet):
""""""
if packet.get("cmd", "") == "UPDATELOG":
self.clear_lists()
return
if self.active is False:
return
if packet.get("cmd", "") == "CALLCHANGED":
call = packet.get("call", "")
self.call = call
self.master_list(call)
self.log_list(call)
return
if packet.get("cmd", "") == "CHECKSPOTS":
call = packet.get("call", "")
self.call = call
self.populate_layout(self.dxcLayout, [])
spots = packet.get("spots", [])
self.telnet_list(spots)
return
if packet.get("cmd", "") == "NEWDB":
...
# self.load_new_db()
def setActive(self, mode: bool):
self.active = bool(mode)
def item_clicked(self, item):
"""docstring for item_clicked"""
if item:
cmd = {}
cmd["cmd"] = "CHANGECALL"
cmd["call"] = item
self.message.emit(cmd)
def load_pref(self) -> None:
"""
Load preference file to get current db filename and sets the initial darkmode state.
Parameters
----------
None
Returns
-------
None
"""
try:
if os.path.exists(fsutils.CONFIG_FILE):
with open(
fsutils.CONFIG_FILE, "rt", encoding="utf-8"
) as file_descriptor:
self.pref = loads(file_descriptor.read())
logger.info(f"loaded config file from {fsutils.CONFIG_FILE}")
else:
self.pref["current_database"] = "ham.db"
except IOError as exception:
logger.critical("Error: %s", exception)
def clear_lists(self) -> None:
"""
Clear match lists.
Parameters
----------
None
Returns
-------
None
"""
self.populate_layout(self.masterLayout, [])
self.populate_layout(self.qsoLayout, [])
self.populate_layout(self.dxcLayout, [])
def master_list(self, call: str) -> None:
"""
Get MASTER.SCP matches to call and display in list.
Parameters
----------
call : str
Call to get matches for
Returns
-------
None
"""
self.populate_layout(self.masterLayout, [])
self.populate_layout(self.masterLayout, self.mscp.super_check(call))
def log_list(self, call: str) -> None:
"""
Get log matches to call and display in list.
Parameters
----------
call : str
Call to get matches for
Returns
-------
None
"""
self.populate_layout(self.qsoLayout, [])
if call:
result = self.database.get_like_calls_and_bands(call)
self.populate_layout(self.qsoLayout, result)
def telnet_list(self, spots: list) -> None:
"""
Get telnet matches to call and display in list.
Parameters
----------
spots : list
List of spots to get matches for
Returns
-------
None
"""
self.populate_layout(self.dxcLayout, [])
if spots:
self.populate_layout(
self.dxcLayout,
filter(lambda x: x, [x.get("callsign", None) for x in spots]),
)
def populate_layout(self, layout, call_list) -> None:
"""Apply blackmagic to a layout."""
for i in reversed(range(layout.count())):
if layout.itemAt(i).widget():
layout.itemAt(i).widget().setParent(None)
else:
layout.removeItem(layout.itemAt(i))
background_colors = self.background_colors_for_mode()
call_items = []
for call in call_list:
if call:
if self.call:
label_text = ""
diff_score = 0
for tag, i1, i2, j1, j2 in Levenshtein.opcodes(call, self.call):
if tag == "equal":
label_text += call[i1:i2]
continue
elif tag == "replace":
label_text += f"{call[i1:i2]}"
diff_score += max((i2 - i1), (j2 - j1)) * (
len(call) + 1 - i2
)
elif tag == "insert" or tag == "delete":
label_text += f"{call[i1:i2]}"
diff_score += max((i2 - i1), (j2 - j1)) * (len(call) - i2)
if call == self.call:
label_text = f"{call}"
call_items.append((diff_score, label_text, call))
call_items = sorted(call_items, key=lambda x: x[0])
for i in reversed(range(layout.count())):
if layout.itemAt(i).widget():
layout.itemAt(i).widget().setParent(None)
else:
layout.removeItem(layout.itemAt(i))
for _, label_text, call in call_items:
label = CallLabel(label_text, call=call, callback=self.item_clicked)
layout.addWidget(label)
layout.addStretch(0)
def background_colors_for_mode(self) -> "CheckWindow.BackgroundColors":
"""Returns appropriate background colors depending on dark or light mode.
These are used for the checkpartial call signs.
"""
if self.background_colors_cache is None:
palette = self.widget.palette()
text_lightness = palette.windowText().color().lightness()
background_lightness = palette.window().color().lightness()
if background_lightness < text_lightness:
# dark mode
self.background_colors_cache = CheckWindow.BackgroundColors(
character_remove_color="#dd3333",
character_add_color="#3333dd",
character_match_color="#33bb33",
)
else:
# light mode
self.background_colors_cache = CheckWindow.BackgroundColors(
character_remove_color="#ffcccc",
character_add_color="#ccccff",
character_match_color="#ccffcc",
)
return self.background_colors_cache
def closeEvent(self, event) -> None:
self.action.setChecked(False)
self.checkwindow_closed.emit()
event.accept()
class CallLabel(QLabel):
call: str = None
def __init__(
self,
*args,
call=None,
callback=None,
):
super().__init__(*args)
self.call = call
self.callback = callback
def mouseReleaseEvent(self, e: QMouseEvent) -> None:
if self.call and self.callback:
self.callback(self.call)
././@PaxHeader 0000000 0000000 0000000 00000000033 00000000000 010211 x ustar 00 27 mtime=1778283194.279071
not1mm-26.5.8/not1mm/data/ 0000755 0001750 0001750 00000000000 15177471272 015034 5 ustar 00mbridak mbridak ././@PaxHeader 0000000 0000000 0000000 00000000026 00000000000 010213 x ustar 00 22 mtime=1747862358.0
not1mm-26.5.8/not1mm/data/JetBrainsMono-Thin.ttf 0000644 0001750 0001750 00001017440 15013441526 021160 0 ustar 00mbridak mbridak GDEF *GPOSXE D #GSUB(Ɉ bOS/2 `cmapZ$X 4 Bjcvt %
n fpgmb/ _ gasp glyf l head+` 6hhea 5W T $hmtxT