Add native QCustomPlot renderer and shared plot adapters
This commit is contained in:
@@ -12,7 +12,7 @@
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define SET_SPECTRUM_MAX 16384U
|
||||
#define SET_SPECTRUM_MAX 2097152U
|
||||
enum { SET_WINDOW_RECT, SET_WINDOW_HANN, SET_WINDOW_HAMMING, SET_WINDOW_BLACKMAN, SET_WINDOW_FLATTOP };
|
||||
enum { SET_FILTER_NONE, SET_FILTER_LOW_PASS, SET_FILTER_HIGH_PASS, SET_FILTER_BAND_PASS, SET_FILTER_NOTCH };
|
||||
enum { SET_SPECTRUM_OK, SET_SPECTRUM_SHORT, SET_SPECTRUM_INVALID, SET_SPECTRUM_TIMING,
|
||||
|
||||
4
cpp/qcustomplot-renderer/.gitignore
vendored
Normal file
4
cpp/qcustomplot-renderer/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
release/
|
||||
debug/
|
||||
Makefile*
|
||||
.qmake.stash
|
||||
674
cpp/qcustomplot-renderer/LICENSE.txt
Normal file
674
cpp/qcustomplot-renderer/LICENSE.txt
Normal file
@@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
46
cpp/qcustomplot-renderer/main.cpp
Normal file
46
cpp/qcustomplot-renderer/main.cpp
Normal file
@@ -0,0 +1,46 @@
|
||||
#include "qcustomplot.h"
|
||||
#include <QApplication>
|
||||
#include <QJsonDocument>
|
||||
#include <QJsonObject>
|
||||
#include <QBuffer>
|
||||
#include <cstdio>
|
||||
#include <iostream>
|
||||
#include <QHash>
|
||||
#include <fcntl.h>
|
||||
#include <io.h>
|
||||
int main(int argc, char **argv) {
|
||||
_setmode(_fileno(stdout), _O_BINARY);
|
||||
QApplication app(argc,argv);
|
||||
QCustomPlot plot;plot.setNotAntialiasedElements(QCP::aeAll);
|
||||
plot.setBackground(Qt::transparent);
|
||||
plot.axisRect()->setBackground(Qt::transparent);
|
||||
plot.axisRect()->setAutoMargins(QCP::msNone);
|
||||
plot.axisRect()->setMargins(QMargins(0,0,0,0));
|
||||
plot.plotLayout()->setMargins(QMargins(0,0,0,0));
|
||||
for(auto axis: plot.axisRect()->axes()) {axis->setVisible(false);axis->grid()->setVisible(false);}
|
||||
auto graph=plot.addGraph(); graph->setAdaptiveSampling(true);
|
||||
QHash<QString,QSharedPointer<QCPGraphDataContainer>> records;
|
||||
std::string line;
|
||||
while(std::getline(std::cin,line)) {
|
||||
auto o=QJsonDocument::fromJson(QByteArray::fromStdString(line)).object();
|
||||
auto path=o["file"].toString();
|
||||
if(!records.contains(path)) {
|
||||
QFile f(path); if(!f.open(QIODevice::ReadOnly)) return 2;
|
||||
int n=o["count"].toInt(); QByteArray bytes=f.readAll();
|
||||
if(bytes.size()!=qint64(n)*16) return 3;
|
||||
QVector<double> x(n),y(n); memcpy(x.data(),bytes.constData(),n*8);memcpy(y.data(),bytes.constData()+n*8,n*8);
|
||||
auto data=QSharedPointer<QCPGraphDataContainer>::create();
|
||||
QVector<QCPGraphData> points(n);for(int i=0;i<n;i++)points[i]=QCPGraphData(x[i],y[i]);
|
||||
data->set(points,false);records.insert(path,data);
|
||||
if(records.size()>4) { auto old=records.begin();if(old.key()==path)++old;records.erase(old); }
|
||||
}
|
||||
graph->setData(records[path]);graph->setPen(QPen(QColor(o["color"].toString()),1));
|
||||
plot.xAxis->setRange(o["left"].toDouble(),o["right"].toDouble());
|
||||
plot.yAxis->setRange(o["bottom"].toDouble(),o["top"].toDouble());
|
||||
int w=o["width"].toInt(),h=o["height"].toInt();
|
||||
plot.resize(w,h);
|
||||
QByteArray png;QBuffer buf(&png);buf.open(QIODevice::WriteOnly);plot.toPixmap(w,h,1.).save(&buf,"PNG");
|
||||
std::cout<<png.size()<<"\n";std::cout.write(png.constData(),png.size());std::cout.flush();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
35539
cpp/qcustomplot-renderer/qcustomplot.cpp
Normal file
35539
cpp/qcustomplot-renderer/qcustomplot.cpp
Normal file
File diff suppressed because it is too large
Load Diff
7781
cpp/qcustomplot-renderer/qcustomplot.h
Normal file
7781
cpp/qcustomplot-renderer/qcustomplot.h
Normal file
File diff suppressed because it is too large
Load Diff
6
cpp/qcustomplot-renderer/renderer.pro
Normal file
6
cpp/qcustomplot-renderer/renderer.pro
Normal file
@@ -0,0 +1,6 @@
|
||||
QT += widgets printsupport
|
||||
CONFIG += c++17 console release
|
||||
CONFIG -= app_bundle
|
||||
SOURCES += main.cpp qcustomplot.cpp
|
||||
HEADERS += qcustomplot.h
|
||||
TARGET = qcp-renderer
|
||||
@@ -1,4 +1,4 @@
|
||||
# Tektronix DPO4034
|
||||
# Tektronix DPO4034 / MDO4034C
|
||||
|
||||
Независимый от Qt драйвер: `python/set_devices/tektronix.py`.
|
||||
Установка: `pip install "setcorp-templates[tektronix]"` из пакета templates.
|
||||
@@ -18,7 +18,7 @@
|
||||
## Реализованный обмен
|
||||
|
||||
Команды SCPI с LF. После открытия `*IDN?` проверяет производителя и точную
|
||||
модель DPO4034; `HEADER OFF` отключает заголовки ответов.
|
||||
модель DPO4034 или MDO4034C; `HEADER OFF` отключает заголовки ответов.
|
||||
|
||||
Для снимка запрашивается `ACQUIRE:STATE?`, затем отправляется
|
||||
`ACQUIRE:STATE STOP` и ожидается `*OPC?`. Это позволяет читать несколько
|
||||
@@ -42,11 +42,11 @@
|
||||
Проверяются конечность коэффициентов, положительный шаг времени и число
|
||||
полученных отсчётов. В `finally` восстанавливается RUN, если до снимка сбор
|
||||
шёл; исходное состояние STOP сохраняется. При ошибке UI закрывает сеанс.
|
||||
Тайм-аут операции VISA — 5 с. Драйвер не сбрасывает настройки прибора.
|
||||
Тайм-аут подключения и операции VISA — 15 с. Драйвер не сбрасывает настройки прибора.
|
||||
|
||||
Снимок читает текущую запись, не ожидает нового аппаратного триггера.
|
||||
DATA:STOP ограничивает начало записи, а не прореживает всю запись.
|
||||
В UI предел 250 000 точек на канал (1 млн суммарно).
|
||||
В UI предел 2 000 000 точек на канал. Длина аппаратной записи задаётся отдельно через HORIZONTAL:RECORDLENGTH; после применения считывается фактическое значение.
|
||||
|
||||
## Пример
|
||||
|
||||
@@ -65,3 +65,6 @@ finally:
|
||||
[MSO4000 / DPO4000 Programmer Manual, 077024801](https://download.tek.com/manual/077024801web.pdf).
|
||||
Проверка с реальным прибором требуется для обоих интерфейсов; офлайн-тесты
|
||||
проверяют последовательность команд, масштабирование, ошибки и восстановление RUN.
|
||||
|
||||
MDO4034C проверен на реальном приборе по Ethernet: идентификация и чтение CH1 (10 000 точек).
|
||||
Команды MDO4034C: [Programmer Manual](https://download.tek.com/manual/MDO4000-B-C-MSO-DPO4000B-and-MDO3000-Oscilloscope-Programmer-Manual-077051007.pdf).
|
||||
|
||||
@@ -9,6 +9,7 @@ See c/set-protocol/include/set_spectrum.h for filtering and normalization semant
|
||||
"""
|
||||
from __future__ import annotations
|
||||
import ctypes
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from enum import IntEnum
|
||||
|
||||
@@ -63,11 +64,40 @@ class NativeSpectrum:
|
||||
self._peak.restype = ctypes.c_int
|
||||
|
||||
def analyze(self, times, values, *, max_size=4096, window=Window.HANN, filter=Filter.NONE,
|
||||
low_hz=10.0, high_hz=100.0, remove_mean=True) -> Spectrum:
|
||||
if type(max_size) is not int or not 16 <= max_size <= 16384 or max_size & (max_size - 1):
|
||||
raise ValueError("FFT size must be a power of two in 16..16384")
|
||||
low_hz=10.0, high_hz=100.0, remove_mean=True, full_record=False) -> Spectrum:
|
||||
if type(max_size) is not int or not 16 <= max_size <= 2097152 or max_size & (max_size - 1):
|
||||
raise ValueError("FFT size must be a power of two in 16..2097152")
|
||||
if len(times) != len(values):
|
||||
raise ValueError("Timestamp and value counts differ")
|
||||
if full_record and len(times) >= 16:
|
||||
source_count = len(times)
|
||||
n = 1 << (min(source_count, max_size).bit_length() - 1)
|
||||
dt = (times[-1] - times[0]) / (source_count - 1)
|
||||
if not math.isfinite(dt) or dt <= 0:
|
||||
raise ValueError("Invalid spectrum timestamps")
|
||||
if any(not math.isfinite(value) for value in values) or any(
|
||||
not math.isfinite(times[i]) or abs((times[i] - times[i - 1]) / dt - 1) > .05
|
||||
for i in range(1, source_count)):
|
||||
raise ValueError("Full-record FFT requires uniformly spaced finite samples")
|
||||
# Integrate piecewise-constant samples over equal fractional bins.
|
||||
# Unlike picking every kth sample, this averages before decimation.
|
||||
width = source_count / n
|
||||
averaged = []
|
||||
index = 0
|
||||
position = 0.
|
||||
for output_index in range(n):
|
||||
end = (output_index + 1) * width
|
||||
total = 0.
|
||||
while position < end and index < source_count:
|
||||
stop = min(end, index + 1.)
|
||||
total += values[index] * (stop - position)
|
||||
position = stop
|
||||
if position >= index + 1:
|
||||
index += 1
|
||||
averaged.append(total / width)
|
||||
start = times[0]
|
||||
times = [start + ((i + .5) * width - .5) * dt for i in range(n)]
|
||||
values = averaged
|
||||
count = min(len(times), max_size)
|
||||
origin = times[len(times) - count] if count else 0.0
|
||||
t = (ctypes.c_double * count)(*(value - origin for value in times[-count:])) if count else (ctypes.c_double * 0)()
|
||||
|
||||
111
python/set_devices/oscilloscope.py
Normal file
111
python/set_devices/oscilloscope.py
Normal file
@@ -0,0 +1,111 @@
|
||||
"""Software oscilloscope capture and sample measurements (timestamps in ms)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
|
||||
|
||||
def time_label(milliseconds):
|
||||
"""Readable time without rounding nanosecond divisions to zero."""
|
||||
magnitude = abs(milliseconds)
|
||||
if magnitude < .001:
|
||||
return f"{milliseconds * 1e6:.6g} нс"
|
||||
if magnitude < 1:
|
||||
return f"{milliseconds * 1000:.6g} мкс"
|
||||
if magnitude < 1000:
|
||||
return f"{milliseconds:.6g} мс"
|
||||
return f"{milliseconds / 1000:.6g} с"
|
||||
|
||||
|
||||
def measurements(points):
|
||||
values = [value for _, value in points if math.isfinite(value)]
|
||||
if not values:
|
||||
return None
|
||||
low, high = min(values), max(values)
|
||||
mean = math.fsum(value / len(values) for value in values)
|
||||
scale = max(abs(low), abs(high))
|
||||
rms = scale * math.sqrt(math.fsum((value / scale) ** 2 for value in values) / len(values)) if scale else 0.
|
||||
# Hysteresis rejects small excursions around the midpoint. Frequency is
|
||||
# only reported after two complete rising crossings, never from one edge.
|
||||
middle = (low + high) / 2
|
||||
hysteresis = (high - low) * .05
|
||||
armed = False
|
||||
crossings = []
|
||||
previous = None
|
||||
if high > low:
|
||||
for stamp, value in points:
|
||||
if value < middle - hysteresis:
|
||||
armed = True
|
||||
if armed and previous and previous[1] < middle <= value and stamp > previous[0]:
|
||||
t0, v0 = previous
|
||||
crossings.append(t0 + (stamp - t0) * (middle - v0) / (value - v0))
|
||||
armed = False
|
||||
previous = (stamp, value)
|
||||
period = ((crossings[-1] - crossings[0]) / (len(crossings) - 1)
|
||||
if len(crossings) >= 2 else None)
|
||||
return dict(minimum=low, maximum=high, peak_to_peak=high - low, mean=mean,
|
||||
rms=rms, frequency=1000 / period if period and period > 0 else None)
|
||||
|
||||
|
||||
class SingleCapture:
|
||||
"""Edge trigger with 20% pretrigger history and 80% posttrigger samples.
|
||||
|
||||
Samples are display-scaled; storage/recording remains owned by the caller.
|
||||
Capture is bounded by the caller's point capacity for each channel.
|
||||
"""
|
||||
def __init__(self):
|
||||
self.cancel()
|
||||
|
||||
def cancel(self):
|
||||
self.armed = False
|
||||
self.trigger_time = None
|
||||
self.previous = None
|
||||
self.data = {}
|
||||
self.truncated = False
|
||||
|
||||
def arm(self, channel, level, falling, span_ms, capacity):
|
||||
self.cancel()
|
||||
self.channel = channel
|
||||
self.level = level
|
||||
self.falling = falling
|
||||
self.span_ms = max(.0001, min(60_000., span_ms))
|
||||
self.capacity = capacity
|
||||
self.armed = True
|
||||
|
||||
def feed(self, stamp, sample, history):
|
||||
"""Return a complete frame once; history must include this sample."""
|
||||
if not self.armed:
|
||||
return None
|
||||
value = sample.get(self.channel)
|
||||
if self.trigger_time is None:
|
||||
previous = self.previous
|
||||
if value is not None:
|
||||
self.previous = (stamp, value)
|
||||
if previous is None or value is None or stamp <= previous[0]:
|
||||
return None
|
||||
crossed = (previous[1] > self.level >= value if self.falling
|
||||
else previous[1] < self.level <= value)
|
||||
if not crossed:
|
||||
return None
|
||||
t0, v0 = previous
|
||||
self.trigger_time = t0 + (stamp - t0) * (self.level - v0) / (value - v0)
|
||||
self.left = self.trigger_time - .2 * self.span_ms
|
||||
self.right = self.trigger_time + .8 * self.span_ms
|
||||
if callable(history):
|
||||
history = history()
|
||||
source = history.get(self.channel, ())
|
||||
self.truncated = not source or source[0][0] - self.trigger_time > -.2 * self.span_ms
|
||||
self.data = {key: [(t, v) for t, v in points
|
||||
if -.2 * self.span_ms <= t - self.trigger_time <= .8 * self.span_ms]
|
||||
for key, points in history.items()}
|
||||
else:
|
||||
for key, value in sample.items():
|
||||
if -.2 * self.span_ms <= stamp - self.trigger_time <= .8 * self.span_ms:
|
||||
points = self.data.setdefault(key, [])
|
||||
if len(points) < self.capacity:
|
||||
points.append((stamp, value))
|
||||
else:
|
||||
self.truncated = True
|
||||
if stamp - self.trigger_time >= .8 * self.span_ms:
|
||||
self.armed = False
|
||||
return self.data
|
||||
return None
|
||||
80
python/set_devices/plot_decimation.py
Normal file
80
python/set_devices/plot_decimation.py
Normal file
@@ -0,0 +1,80 @@
|
||||
"""Pixel-column envelope for drawing; measurement samples are never changed."""
|
||||
import math
|
||||
from bisect import bisect_left, bisect_right
|
||||
|
||||
|
||||
class IndexedTimes(list):
|
||||
"""Random-access timestamps, with ordering validated once when loaded."""
|
||||
def __init__(self, points):
|
||||
super().__init__(points)
|
||||
self.ordered = all(math.isfinite(x) and (i == 0 or self[i-1] <= x)
|
||||
for i, x in enumerate(self))
|
||||
|
||||
|
||||
def viewport_samples(timestamps, values, left, right, neighbours=False, budget=None):
|
||||
"""Select only the viewport in logarithmic time for indexed records."""
|
||||
if isinstance(timestamps, (list, tuple, range)) and getattr(timestamps, "ordered", True):
|
||||
start = bisect_left(timestamps, left)
|
||||
stop = bisect_right(timestamps, right)
|
||||
if neighbours:
|
||||
start = max(0, start - 1)
|
||||
stop = min(len(timestamps), stop + 1)
|
||||
stride = max(1, math.ceil((stop-start) / budget)) if budget else 1
|
||||
for i in range(start, min(stop, len(values)), stride):
|
||||
yield timestamps[i], values[i]
|
||||
if budget and stop > start and (stop - 1 - start) % stride:
|
||||
yield timestamps[stop-1], values[stop-1]
|
||||
else:
|
||||
# Streaming or unordered data keeps its original gap/order semantics.
|
||||
yield from zip(timestamps, values)
|
||||
|
||||
|
||||
|
||||
def pixel_envelope(timestamps, values, left, right, width):
|
||||
"""Yield first/min/max/last samples in time order for each pixel column.
|
||||
|
||||
NaNs separate paths. Keep one neighbouring sample on either side so clipping
|
||||
and zooming retain lines crossing the viewport boundaries.
|
||||
"""
|
||||
width = max(1, int(width))
|
||||
scale = width / (right - left) if right > left else 1.
|
||||
bucket = None
|
||||
first = low = high = last = None
|
||||
|
||||
def emit():
|
||||
if first is None:
|
||||
return ()
|
||||
selected = {point[0]: point for point in (first, low, high, last)}
|
||||
return tuple((selected[index][1], selected[index][2]) for index in sorted(selected))
|
||||
|
||||
for index, (stamp, value) in enumerate(viewport_samples(timestamps, values, left, right, neighbours=True)):
|
||||
if not math.isfinite(stamp) or not math.isfinite(value):
|
||||
yield from emit()
|
||||
yield None
|
||||
bucket = None
|
||||
first = low = high = last = None
|
||||
continue
|
||||
column = -1 if stamp < left else width if stamp > right else min(width - 1, int((stamp - left) * scale))
|
||||
point = (index, stamp, value)
|
||||
if column != bucket:
|
||||
yield from emit()
|
||||
bucket = column
|
||||
first = low = high = last = point
|
||||
elif column == -1:
|
||||
first = low = high = last = point
|
||||
elif column == width:
|
||||
continue
|
||||
else:
|
||||
last = point
|
||||
if value < low[2]:
|
||||
low = point
|
||||
if value > high[2]:
|
||||
high = point
|
||||
yield from emit()
|
||||
|
||||
|
||||
def preview_window_count(requested, preview_count, original_count):
|
||||
"""Translate a raw-sample window to a display-envelope window."""
|
||||
if not original_count or original_count <= preview_count:
|
||||
return requested
|
||||
return max(1, min(preview_count, math.ceil(requested * preview_count / original_count)))
|
||||
@@ -100,7 +100,10 @@ class PlotDragInteraction:
|
||||
self.viewport = self._press_viewport.transform(self.core,
|
||||
pan_x=delta.x() / rect.width() if not self.lock_x else 0)
|
||||
self._refresh_controls()
|
||||
self.update()
|
||||
if self._dragged is not None:
|
||||
getattr(self, "update_overlay", self.update)()
|
||||
else:
|
||||
self.update()
|
||||
|
||||
def mouseReleaseEvent(self, event):
|
||||
if event.button() != Qt.LeftButton:
|
||||
|
||||
@@ -157,8 +157,8 @@ class DualAxisPlot:
|
||||
self._navigation_zoom(factor, True, pos)
|
||||
event.accept()
|
||||
|
||||
def paint_axes_and_markers(self, painter):
|
||||
super().paint_axes_and_markers(painter)
|
||||
def paint_axes(self, painter):
|
||||
super().paint_axes(painter)
|
||||
if not self.right_axis_keys or not self.core:
|
||||
return
|
||||
paint_right_axis(painter, self.core, self.value_rect(), self.right_visible_bounds)
|
||||
@@ -188,7 +188,7 @@ class SingleAmplitudeAxis:
|
||||
rect.setWidth(max(1, rect.width() - 72))
|
||||
return rect
|
||||
|
||||
def paint_axes_and_markers(self, painter):
|
||||
super().paint_axes_and_markers(painter)
|
||||
def paint_axes(self, painter):
|
||||
super().paint_axes(painter)
|
||||
if self.core and not self.has_left_axis():
|
||||
paint_right_axis(painter, self.core, self.value_rect(), self.visible_bounds)
|
||||
|
||||
46
python/set_devices/qt_ports/plot_layers.py
Normal file
46
python/set_devices/qt_ports/plot_layers.py
Normal file
@@ -0,0 +1,46 @@
|
||||
"""Queued redraws and cached static layers for Qt plots (Qt 5/6)."""
|
||||
try:
|
||||
from PySide6.QtCore import QTimer, Qt
|
||||
from PySide6.QtGui import QPixmap, QPainter
|
||||
except ImportError:
|
||||
from PySide2.QtCore import QTimer, Qt
|
||||
from PySide2.QtGui import QPixmap, QPainter
|
||||
|
||||
class PlotLayers:
|
||||
def init_plot_layers(self):
|
||||
self._static_revision = 0
|
||||
self._static_plot_layer = None
|
||||
self._redraw_timer = QTimer(self)
|
||||
self._redraw_timer.setSingleShot(True)
|
||||
self._redraw_timer.timeout.connect(self._flush_plot_update)
|
||||
|
||||
def update(self, *args):
|
||||
if not hasattr(self, '_redraw_timer'):
|
||||
return super().update(*args)
|
||||
self._static_revision += 1
|
||||
self.update_overlay()
|
||||
|
||||
def update_overlay(self):
|
||||
if not hasattr(self, '_redraw_timer'):
|
||||
return super().update()
|
||||
if not self._redraw_timer.isActive():
|
||||
self._redraw_timer.start(0)
|
||||
|
||||
def _flush_plot_update(self):
|
||||
super().update()
|
||||
|
||||
def paint_static_layer(self, painter, draw):
|
||||
ratio = self.devicePixelRatioF()
|
||||
key = (self._static_revision, self.width(), self.height(), ratio,
|
||||
tuple(self.plot_rect().getRect()))
|
||||
if self._static_plot_layer is None or self._static_plot_layer[0] != key:
|
||||
image = QPixmap(round(self.width()*ratio), round(self.height()*ratio))
|
||||
image.setDevicePixelRatio(ratio)
|
||||
image.fill(Qt.GlobalColor.transparent)
|
||||
layer = QPainter(image)
|
||||
try:
|
||||
draw(layer)
|
||||
finally:
|
||||
layer.end()
|
||||
self._static_plot_layer = key, image
|
||||
painter.drawPixmap(0, 0, self._static_plot_layer[1])
|
||||
@@ -64,6 +64,7 @@ class SignalProcessingPanel(QWidget):
|
||||
self._revision = 0
|
||||
self._job_revision = 0
|
||||
self.preserve_on_view_change = False
|
||||
self.preserve_on_data_change = False
|
||||
self.export_path = lambda filename: filename
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(0, 0, 0, 0)
|
||||
@@ -153,7 +154,7 @@ class SignalProcessingPanel(QWidget):
|
||||
# depend on samples/units, not the source curve's checkbox.
|
||||
source = replace(source, series=tuple(replace(series, visible=True)
|
||||
for series in source.series))
|
||||
if prepare(source, request.series.key, request.method, request.output_count, request.degree) == request:
|
||||
if self.preserve_on_data_change or prepare(source, request.series.key, request.method, request.output_count, request.degree) == request:
|
||||
retained.append(result)
|
||||
if len(retained) != len(self._results):
|
||||
self._results = retained
|
||||
|
||||
53
python/set_devices/qt_ports/plot_workers.py
Normal file
53
python/set_devices/qt_ports/plot_workers.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""Reusable background workers for dense plots and viewport measurements."""
|
||||
try:
|
||||
from PySide6.QtCore import QObject, QRunnable, Signal
|
||||
except ImportError:
|
||||
from PySide2.QtCore import QObject, QRunnable, Signal
|
||||
from set_devices.plot_decimation import pixel_envelope, viewport_samples
|
||||
from set_devices.oscilloscope import measurements
|
||||
|
||||
class EnvelopeSignals(QObject):
|
||||
ready = Signal(str, object, object)
|
||||
|
||||
|
||||
class EnvelopeJob(QRunnable):
|
||||
def __init__(self, key, geometry, timestamps, values, left, right, width, signals):
|
||||
super().__init__()
|
||||
self.args = (timestamps, values, left, right, width)
|
||||
self.key, self.geometry, self.signals = key, geometry, signals
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
points = tuple(pixel_envelope(*self.args))
|
||||
except Exception:
|
||||
points = None
|
||||
try:
|
||||
self.signals.ready.emit(self.key, self.geometry, points)
|
||||
except RuntimeError:
|
||||
pass # The plot may have been closed while the worker was running.
|
||||
|
||||
|
||||
class NavigationSignals(QObject):
|
||||
ready = Signal(int, object, object)
|
||||
|
||||
|
||||
class NavigationJob(QRunnable):
|
||||
def __init__(self, revision, series, bounds, emitter):
|
||||
super().__init__()
|
||||
self.revision, self.series, self.bounds, self.emitter = revision, series, bounds, emitter
|
||||
|
||||
def run(self):
|
||||
stats = {}
|
||||
try:
|
||||
for key, times, values in self.series:
|
||||
points = [(x, y) for x, y in viewport_samples(times, values, self.bounds.left, self.bounds.right)
|
||||
if self.bounds.left <= x <= self.bounds.right]
|
||||
stats[key] = measurements(points), len(points)
|
||||
self.emitter.ready.emit(self.revision, stats, self.bounds)
|
||||
except Exception:
|
||||
try:
|
||||
self.emitter.ready.emit(self.revision, {}, self.bounds)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
|
||||
88
python/set_devices/qt_ports/qcustomplot_renderer.py
Normal file
88
python/set_devices/qt_ports/qcustomplot_renderer.py
Normal file
@@ -0,0 +1,88 @@
|
||||
"""Isolated native QCustomPlot renderer; no Qt ABI mixing with PySide."""
|
||||
from array import array
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
from threading import Lock
|
||||
try:
|
||||
from PySide6.QtCore import QObject, QRunnable, Signal
|
||||
except ImportError:
|
||||
from PySide2.QtCore import QObject, QRunnable, Signal
|
||||
|
||||
class NativePlotSignals(QObject):
|
||||
ready = Signal(str, object, object)
|
||||
|
||||
class NativePlotEngine:
|
||||
def __init__(self, executable):
|
||||
self.executable = Path(executable)
|
||||
self.process = None
|
||||
self.closed = False
|
||||
self.lock = Lock()
|
||||
self.directory = tempfile.TemporaryDirectory(prefix='setgui-qcp-')
|
||||
self.records = {}
|
||||
self.serial = 0
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
if self.process is not None:
|
||||
self.process.kill()
|
||||
if self.process.stdin is not None:
|
||||
self.process.stdin.close()
|
||||
# Files are owned by this TemporaryDirectory and released with the engine.
|
||||
|
||||
def render(self, times, values, bounds, width, height, color):
|
||||
with self.lock:
|
||||
if self.closed:
|
||||
raise RuntimeError("Plot closed")
|
||||
if self.process is None or self.process.poll() is not None:
|
||||
env = os.environ.copy()
|
||||
env['QT_QPA_PLATFORM'] = 'offscreen'
|
||||
env.pop('QT_PLUGIN_PATH', None)
|
||||
env['QT_QPA_PLATFORM_PLUGIN_PATH'] = str(self.executable.parent / 'platforms')
|
||||
self.process = subprocess.Popen([str(self.executable)], stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env, bufsize=0,
|
||||
creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0), cwd=self.executable.parent)
|
||||
key = (id(times), id(values))
|
||||
record = self.records.get(key)
|
||||
if record is None:
|
||||
self.serial += 1
|
||||
path = Path(self.directory.name) / f'{self.serial}.bin'
|
||||
with path.open('wb') as stream:
|
||||
array('d', times).tofile(stream)
|
||||
array('d', values).tofile(stream)
|
||||
record = (path, times, values)
|
||||
self.records[key] = record
|
||||
if len(self.records) > 4:
|
||||
self.records.pop(next(iter(self.records)))
|
||||
request = dict(file=str(record[0]), count=len(times), width=width, height=height,
|
||||
left=bounds.left, right=bounds.right, bottom=bounds.bottom, top=bounds.top, color=color)
|
||||
self.process.stdin.write((json.dumps(request)+'\n').encode())
|
||||
self.process.stdin.flush()
|
||||
size = int(self.process.stdout.readline())
|
||||
if not 0 < size < 100_000_000:
|
||||
raise RuntimeError('Invalid QCustomPlot frame')
|
||||
chunks = bytearray()
|
||||
while len(chunks) < size:
|
||||
chunk = self.process.stdout.read(size-len(chunks))
|
||||
if not chunk:
|
||||
raise RuntimeError('QCustomPlot renderer stopped')
|
||||
chunks.extend(chunk)
|
||||
return bytes(chunks)
|
||||
|
||||
class NativePlotJob(QRunnable):
|
||||
def __init__(self, engine, key, geometry, times, values, bounds, width, height, color, signals):
|
||||
super().__init__()
|
||||
self.engine, self.key, self.geometry, self.signals = engine, key, geometry, signals
|
||||
self.args = times, values, bounds, width, height, color
|
||||
|
||||
def run(self):
|
||||
try:
|
||||
png = self.engine.render(*self.args)
|
||||
except Exception:
|
||||
png = None
|
||||
try:
|
||||
self.signals.ready.emit(self.key, self.geometry, png)
|
||||
except RuntimeError:
|
||||
pass
|
||||
24
python/set_devices/qt_ports/tektronix_controls.py
Normal file
24
python/set_devices/qt_ports/tektronix_controls.py
Normal file
@@ -0,0 +1,24 @@
|
||||
"""Tektronix-style record-length selector, including instrument readback."""
|
||||
try:
|
||||
from PySide6.QtWidgets import QComboBox
|
||||
except ImportError:
|
||||
from PySide2.QtWidgets import QComboBox
|
||||
from set_devices.tektronix_presets import RECORD_LENGTHS
|
||||
|
||||
|
||||
class RecordLengthBox(QComboBox):
|
||||
def __init__(self, parent=None):
|
||||
super().__init__(parent)
|
||||
for value in RECORD_LENGTHS:
|
||||
self.addItem(f"{value:,}".replace(",", " ") + " точек", value)
|
||||
|
||||
def value(self):
|
||||
return int(self.currentData())
|
||||
|
||||
def setValue(self, value):
|
||||
value = int(value)
|
||||
index = self.findData(value)
|
||||
if index < 0:
|
||||
self.addItem(f"{value:,}".replace(",", " ") + " точек", value)
|
||||
index = self.count() - 1
|
||||
self.setCurrentIndex(index)
|
||||
82
python/set_devices/qt_ports/viewport_navigation.py
Normal file
82
python/set_devices/qt_ports/viewport_navigation.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""Debounced viewport statistics shared by desktop charts."""
|
||||
import time
|
||||
from dataclasses import replace
|
||||
try:
|
||||
from PySide6.QtCore import QObject, QTimer, QThreadPool, Qt
|
||||
except ImportError:
|
||||
from PySide2.QtCore import QObject, QTimer, QThreadPool, Qt
|
||||
from .plot_workers import NavigationSignals as _NavigationSignals, NavigationJob as _NavigationJob
|
||||
from set_devices.oscilloscope import time_label
|
||||
def number(value):
|
||||
return f"{value:g}"
|
||||
|
||||
class ViewportNavigation(QObject):
|
||||
def __init__(self, chart):
|
||||
super().__init__(chart)
|
||||
self.chart = chart
|
||||
self._navigation_revision = 0
|
||||
self._navigation_busy = False
|
||||
self._navigation_emitter = _NavigationSignals(self)
|
||||
self._navigation_emitter.ready.connect(self._navigation_ready, Qt.ConnectionType.QueuedConnection)
|
||||
self._navigation_timer = QTimer(self)
|
||||
self._navigation_timer.setSingleShot(True)
|
||||
self._navigation_timer.setInterval(180)
|
||||
self._navigation_timer.timeout.connect(self._navigation_finished)
|
||||
|
||||
def _navigation_changed(self):
|
||||
self._navigation_revision += 1
|
||||
if max((len(s.values) for s in self.chart.plot._series), default=0) <= 20000:
|
||||
self.chart._scope_measurements()
|
||||
self.chart._refresh_processing()
|
||||
self.chart._refresh_legend()
|
||||
return
|
||||
self._navigation_timer.start()
|
||||
|
||||
def _navigation_finished(self):
|
||||
if False:
|
||||
return
|
||||
if max((len(s.values) for s in self.chart.plot._series), default=0) <= 20000:
|
||||
self.chart._scope_measurements()
|
||||
self.chart._refresh_processing()
|
||||
return
|
||||
if self._navigation_busy:
|
||||
self._navigation_timer.start()
|
||||
return
|
||||
self._navigation_busy = True
|
||||
bounds = self.chart.plot.visible_bounds
|
||||
panel = self.chart.processing
|
||||
offset = self.chart._plot_time_offset if not self.chart.fft.isChecked() else 0.
|
||||
# Navigation changes the next calculation's domain; retained curves keep
|
||||
# their original domain. Avoid preparing millions of inputs on the UI.
|
||||
panel._snapshot = replace(panel._snapshot, x_range=(bounds.left + offset, bounds.right + offset))
|
||||
series = [(s.key, s.timestamps, s.values) for s in self.chart.plot._series if not s.discrete]
|
||||
QThreadPool.globalInstance().start(_NavigationJob(self._navigation_revision, series, bounds,
|
||||
self._navigation_emitter))
|
||||
|
||||
def _navigation_ready(self, revision, stats, bounds):
|
||||
self._navigation_busy = False
|
||||
if False or revision != self._navigation_revision:
|
||||
return
|
||||
for row in range(self.chart.legend.rowCount()):
|
||||
item = self.chart.legend.item(row, 0)
|
||||
if item is None:
|
||||
continue
|
||||
result, _ = stats.get(item.data(Qt.ItemDataRole.UserRole), (None, 0))
|
||||
for column, key in ((4, "rms"), (5, "maximum"), (6, "minimum")):
|
||||
cell = self.chart.legend.item(row, column)
|
||||
if cell is not None:
|
||||
cell.setText("—" if result is None else "%g" % result[key])
|
||||
scope = self.chart.scope
|
||||
result, count = stats.get(scope.channel.currentData(), (None, 0))
|
||||
if result is None:
|
||||
scope.readings.setText("Измерения: —")
|
||||
return
|
||||
text = " · ".join(f"{title} {number(result[key])}" for title, key in (
|
||||
("Min", "minimum"), ("Max", "maximum"), ("Размах", "peak_to_peak"),
|
||||
("Среднее", "mean"), ("RMS", "rms")))
|
||||
if not self.chart.fft.isChecked():
|
||||
frequency = result["frequency"]
|
||||
text += " · f ≈ " + (f"{number(frequency)} Гц" if frequency is not None else "—")
|
||||
text += f" · {time_label((bounds.right - bounds.left) / 10)}/дел"
|
||||
scope.readings.setText(text + f" · N={count}")
|
||||
|
||||
@@ -45,7 +45,7 @@ class DPO4034:
|
||||
self.manager = None
|
||||
self.instrument = None
|
||||
|
||||
def connect(self, resource, timeout_ms=5000):
|
||||
def connect(self, resource, timeout_ms=15000):
|
||||
self.close()
|
||||
factory = self._factory
|
||||
if factory is None:
|
||||
@@ -62,8 +62,8 @@ class DPO4034:
|
||||
self.instrument.read_termination = "\n"
|
||||
identity = self.instrument.query("*IDN?").strip()
|
||||
fields = identity.upper().split(",")
|
||||
if len(fields) < 2 or "TEKTRONIX" not in fields[0] or fields[1].strip() != "DPO4034":
|
||||
raise ValueError(f"Ожидался Tektronix DPO4034, получено: {identity}")
|
||||
if len(fields) < 2 or "TEKTRONIX" not in fields[0] or fields[1].strip() not in ("DPO4034", "MDO4034C"):
|
||||
raise ValueError(f"Ожидался Tektronix DPO4034 или MDO4034C, получено: {identity}")
|
||||
self.instrument.write("HEADER OFF")
|
||||
return identity
|
||||
except Exception:
|
||||
@@ -80,38 +80,140 @@ class DPO4034:
|
||||
if manager is not None:
|
||||
manager.close()
|
||||
|
||||
def capture(self, channels, points=100000):
|
||||
@staticmethod
|
||||
def _channel(channel):
|
||||
if channel not in ("CH1", "CH2", "CH3", "CH4"):
|
||||
raise ValueError("Выберите канал CH1…CH4")
|
||||
return channel
|
||||
|
||||
def settings(self, channel="CH1"):
|
||||
self._channel(channel)
|
||||
if self.instrument is None:
|
||||
raise RuntimeError("Прибор не подключён")
|
||||
commands = ["TRIGGER:A:TYPE?", "TRIGGER:A:MODE?", "TRIGGER:A:EDGE:SOURCE?",
|
||||
"TRIGGER:A:EDGE:SLOPE?", f"TRIGGER:A:LEVEL:{channel}?",
|
||||
"HORIZONTAL:SCALE?", f"SELECT:{channel}?", f"{channel}:SCALE?",
|
||||
f"{channel}:POSITION?", f"{channel}:COUPLING?", "ACQUIRE:MODE?",
|
||||
"ACQUIRE:NUMAVG?", "ACQUIRE:STATE?", "TRIGGER:STATE?", "HORIZONTAL:RECORDLENGTH?"]
|
||||
values = self.instrument.query(";:".join(commands)).strip().split(";")
|
||||
if len(values) != len(commands):
|
||||
raise ValueError("Некорректный ответ настроек прибора")
|
||||
keys = ("trigger_type", "trigger_mode", "trigger_source", "trigger_slope", "trigger_level",
|
||||
"time_scale", "channel_enabled", "channel_scale", "channel_position", "coupling",
|
||||
"acquire_mode", "averages", "running", "trigger_state", "record_length")
|
||||
result = dict(zip(keys, (v.strip().strip('"') for v in values)))
|
||||
result["channel"] = channel
|
||||
for key in ("trigger_level", "time_scale", "channel_scale", "channel_position"):
|
||||
result[key] = float(result[key])
|
||||
if not math.isfinite(result[key]):
|
||||
raise ValueError("Некорректное числовое значение настроек")
|
||||
for key in ("channel_enabled", "averages", "running", "record_length"):
|
||||
result[key] = int(result[key])
|
||||
source = result["trigger_source"]
|
||||
if source in ("CH1", "CH2", "CH3", "CH4") and source != channel:
|
||||
result["trigger_level"] = float(self.instrument.query(f"TRIGGER:A:LEVEL:{source}?").strip())
|
||||
return result
|
||||
|
||||
def configure(self, section, values, channel="CH1"):
|
||||
self._channel(channel)
|
||||
if self.instrument is None:
|
||||
raise RuntimeError("Прибор не подключён")
|
||||
def number(key, positive=False):
|
||||
value = float(values[key])
|
||||
if not math.isfinite(value) or (positive and value <= 0):
|
||||
raise ValueError("Некорректное значение: " + key)
|
||||
return format(value, ".12g")
|
||||
def choice(key, allowed):
|
||||
value = values[key]
|
||||
if value not in allowed:
|
||||
raise ValueError("Некорректное значение: " + key)
|
||||
return value
|
||||
if section == "preset":
|
||||
from .tektronix_presets import PRESETS
|
||||
if values.get("preset") not in PRESETS:
|
||||
raise ValueError("Неизвестный пресет")
|
||||
preset = PRESETS[values["preset"]]
|
||||
commands = ["ACQUIRE:MODE " + preset["mode"],
|
||||
"HORIZONTAL:RECORDLENGTH " + str(preset["record_length"])]
|
||||
if preset["live"]:
|
||||
commands += ["SELECT:CH1 ON", "ACQUIRE:STOPAFTER RUNSTOP", "ACQUIRE:STATE RUN"]
|
||||
elif section == "trigger":
|
||||
source = self._channel(values["source"])
|
||||
commands = ["TRIGGER:A:TYPE EDGE", "TRIGGER:A:MODE " + choice("mode", ("AUTO", "NORMAL")),
|
||||
"TRIGGER:A:EDGE:SOURCE " + source,
|
||||
"TRIGGER:A:EDGE:SLOPE " + choice("slope", ("RISE", "FALL", "EITHER")),
|
||||
f"TRIGGER:A:LEVEL:{source} " + number("level")]
|
||||
channel = source
|
||||
elif section == "horizontal":
|
||||
commands = ["HORIZONTAL:SCALE " + number("scale", True)]
|
||||
elif section == "record":
|
||||
length = int(values["length"])
|
||||
if not 1000 <= length <= 20000000:
|
||||
raise ValueError("Длина записи должна быть 1000…20000000 точек")
|
||||
commands = [f"HORIZONTAL:RECORDLENGTH {length}"]
|
||||
elif section == "channel":
|
||||
commands = [f"SELECT:{channel} " + choice("enabled", ("ON", "OFF")),
|
||||
f"{channel}:SCALE " + number("scale", True),
|
||||
f"{channel}:POSITION " + number("position"),
|
||||
f"{channel}:COUPLING " + choice("coupling", ("AC", "DC", "GND"))]
|
||||
elif section == "acquisition":
|
||||
averages = int(values["averages"])
|
||||
if averages not in (2, 4, 8, 16, 32, 64, 128, 256, 512):
|
||||
raise ValueError("Число усреднений: 2…512, степень двойки")
|
||||
commands = ["ACQUIRE:MODE " + choice("mode", ("SAMPLE", "AVERAGE", "HIRES")),
|
||||
f"ACQUIRE:NUMAVG {averages}"]
|
||||
else:
|
||||
raise ValueError("Неизвестный раздел настроек")
|
||||
self.instrument.write(";:".join(commands))
|
||||
return self.settings(channel)
|
||||
|
||||
def acquisition(self, action, channel="CH1"):
|
||||
self._channel(channel)
|
||||
if self.instrument is None:
|
||||
raise RuntimeError("Прибор не подключён")
|
||||
commands = {"run": "ACQUIRE:STOPAFTER RUNSTOP;:ACQUIRE:STATE RUN",
|
||||
"stop": "ACQUIRE:STATE STOP",
|
||||
"single": "ACQUIRE:STATE STOP;:ACQUIRE:STOPAFTER SEQUENCE;:ACQUIRE:STATE RUN"}
|
||||
if action not in commands:
|
||||
raise ValueError("Неизвестная команда сбора")
|
||||
self.instrument.write(commands[action])
|
||||
# Do not wait for *OPC?: a single acquisition may wait indefinitely for a trigger.
|
||||
return self.settings(channel)
|
||||
|
||||
def capture(self, channels, points=100000, live=False):
|
||||
channels = tuple(channels)
|
||||
if not channels or len(set(channels)) != len(channels) or any(c not in ("CH1", "CH2", "CH3", "CH4") for c in channels):
|
||||
raise ValueError("Выберите каналы CH1…CH4")
|
||||
if not 1 <= points <= 1000000:
|
||||
raise ValueError("Число точек должно быть 1…1000000")
|
||||
if live and len(channels) != 1:
|
||||
raise ValueError("Быстрое чтение поддерживает один канал")
|
||||
if not 1 <= points <= 2000000:
|
||||
raise ValueError("Число точек должно быть 1…2000000")
|
||||
scope = self.instrument
|
||||
if scope is None:
|
||||
raise RuntimeError("Прибор не подключён")
|
||||
# Freeze the record so all selected channels belong to the same capture.
|
||||
running = int(scope.query("ACQUIRE:STATE?").strip())
|
||||
running = 0 if live else int(scope.query("ACQUIRE:STATE?").strip())
|
||||
result = []
|
||||
try:
|
||||
scope.write("ACQUIRE:STATE STOP")
|
||||
scope.query("*OPC?")
|
||||
if not live:
|
||||
scope.query("ACQUIRE:STATE STOP;*OPC?")
|
||||
for channel in channels:
|
||||
if not int(scope.query(f"SELECT:{channel}?").strip()):
|
||||
scope.write(f"DATA:SOURCE {channel};:DATA:ENCDG RIBINARY;:DATA:WIDTH 2;:DATA:START 1;:DATA:STOP {points}")
|
||||
keys = ("PT_FMT", "XINCR", "XZERO", "PT_OFF", "YMULT", "YOFF", "YZERO", "YUNIT", "NR_PT")
|
||||
query = f"SELECT:{channel}?;" + ";".join(f":WFMOUTPRE:{key}?" for key in keys)
|
||||
fields = scope.query(query).strip().split(";")
|
||||
if len(fields) != 10:
|
||||
raise ValueError("Некорректный ответ преамбулы осциллограммы")
|
||||
if not int(fields[0]):
|
||||
raise ValueError(f"Включите {channel} на осциллографе")
|
||||
scope.write(f"DATA:SOURCE {channel}")
|
||||
scope.write("DATA:ENCDG RIBINARY")
|
||||
scope.write("DATA:WIDTH 2")
|
||||
scope.write("DATA:START 1")
|
||||
scope.write(f"DATA:STOP {points}")
|
||||
if scope.query("WFMOUTPRE:PT_FMT?").strip().upper() != "Y":
|
||||
if fields[1].strip().upper() != "Y":
|
||||
raise ValueError("ENV/Peak Detect не поддерживается; выберите Sample или Average")
|
||||
params = [float(scope.query(f"WFMOUTPRE:{key}?").strip()) for key in
|
||||
("XINCR", "XZERO", "PT_OFF", "YMULT", "YOFF", "YZERO")]
|
||||
params = [float(value) for value in fields[2:8]]
|
||||
dx, x0, offset, mult, yoff, y0 = params
|
||||
if not all(math.isfinite(v) for v in params) or dx <= 0:
|
||||
raise ValueError("Некорректная преамбула осциллограммы")
|
||||
unit = scope.query("WFMOUTPRE:YUNIT?").strip().strip('"')
|
||||
count = int(scope.query("WFMOUTPRE:NR_PT?").strip())
|
||||
unit = fields[8].strip().strip('"')
|
||||
count = int(fields[9].strip())
|
||||
if not 1 <= count <= points:
|
||||
raise ValueError("Некорректная длина осциллограммы")
|
||||
raw = scope.query_binary_values("CURVE?", datatype="h", is_big_endian=True,
|
||||
|
||||
8
python/set_devices/tektronix_presets.py
Normal file
8
python/set_devices/tektronix_presets.py
Normal file
@@ -0,0 +1,8 @@
|
||||
"""Shared acquisition presets for supported Tektronix scopes."""
|
||||
PRESETS = {
|
||||
"live": dict(label="Живой просмотр", mode="SAMPLE", record_length=10000,
|
||||
transfer_points=10000, averages=16, live=True, preview=True, repeat=True, pause_ms=0),
|
||||
"long": dict(label="Длинная запись / FFT", mode="SAMPLE", record_length=1000000,
|
||||
transfer_points=1000000, averages=16, live=False, preview=True, repeat=False, pause_ms=0),
|
||||
}
|
||||
RECORD_LENGTHS = (1000, 10000, 100000, 1000000, 5000000, 10000000, 20000000)
|
||||
79
python/set_devices/tektronix_session.py
Normal file
79
python/set_devices/tektronix_session.py
Normal file
@@ -0,0 +1,79 @@
|
||||
"""Qt-independent capture queue, preview and full-record CSV export."""
|
||||
from dataclasses import dataclass
|
||||
from queue import Queue
|
||||
from threading import Thread
|
||||
import csv
|
||||
from .tektronix import DPO4034, Waveform
|
||||
from .plot_decimation import pixel_envelope
|
||||
|
||||
@dataclass
|
||||
class CaptureFrame:
|
||||
full: list
|
||||
preview: list
|
||||
|
||||
|
||||
def prepare_preview(waveforms, width):
|
||||
preview = []
|
||||
for wave in waveforms:
|
||||
if not wave.seconds:
|
||||
preview.append(wave)
|
||||
continue
|
||||
points = [point for point in pixel_envelope(wave.seconds, wave.values,
|
||||
wave.seconds[0], wave.seconds[-1], width) if point is not None]
|
||||
preview.append(Waveform(wave.channel, tuple(x for x, _ in points),
|
||||
tuple(y for _, y in points), wave.unit))
|
||||
return preview
|
||||
|
||||
|
||||
class ScopeSession:
|
||||
"""Serial worker queue: every VISA call, including close, stays off the UI."""
|
||||
|
||||
def __init__(self, factory=DPO4034):
|
||||
self.commands = Queue()
|
||||
self.results = Queue()
|
||||
self.thread = Thread(target=self._run, args=(factory,))
|
||||
self.thread.start()
|
||||
|
||||
def _run(self, factory):
|
||||
client = factory()
|
||||
try:
|
||||
while True:
|
||||
action, args = self.commands.get()
|
||||
if action == "shutdown":
|
||||
break
|
||||
try:
|
||||
if action == "capture" and len(args) == 4:
|
||||
value = client.capture(*args[:3])
|
||||
value = CaptureFrame(value, prepare_preview(value, args[3]))
|
||||
elif action == "export":
|
||||
filename, waves = args
|
||||
with open(filename, "w", newline="", encoding="utf-8-sig") as stream:
|
||||
writer = csv.writer(stream)
|
||||
# Native channels share the frozen record's time grid.
|
||||
# Reject mismatched grids rather than misalign exported values.
|
||||
if any(w.seconds != waves[0].seconds for w in waves[1:]):
|
||||
raise ValueError("Для экспорта каналов нужны одинаковые временные сетки")
|
||||
writer.writerow(["time_ms", *(w.channel + " (" + w.unit + ")" for w in waves)])
|
||||
for index, stamp in enumerate(waves[0].seconds):
|
||||
writer.writerow([stamp * 1000, *(w.values[index] for w in waves)])
|
||||
value = filename
|
||||
else:
|
||||
value = getattr(client, action)(*args)
|
||||
self.results.put((action, value, None))
|
||||
except Exception as exc:
|
||||
if action != "export":
|
||||
try:
|
||||
client.close()
|
||||
except Exception:
|
||||
pass
|
||||
self.results.put((action, None, str(exc)))
|
||||
finally:
|
||||
try:
|
||||
client.close()
|
||||
except Exception:
|
||||
pass # Shutdown must finish even if the device has been unplugged.
|
||||
|
||||
def submit(self, action, *args):
|
||||
self.commands.put((action, args))
|
||||
|
||||
|
||||
@@ -30,6 +30,26 @@ class SpectrumTests(unittest.TestCase):
|
||||
times = [i / fs for i in range(n)]
|
||||
return times, [amplitude * sum(math.sin(2 * math.pi * f * t) for f in frequencies) for t in times]
|
||||
|
||||
def test_large_fft_above_previous_limit(self):
|
||||
times, values = self.sample(n=65536, fs=65536, frequencies=(50,))
|
||||
spectrum = self.core.analyze(times, values, max_size=65536)
|
||||
self.assertEqual(spectrum.size, 65536)
|
||||
self.assertAlmostEqual(self.core.dominant_peak(spectrum).frequency_hz, 50., delta=.01)
|
||||
self.assertEqual(self.core.analyze(times[:1024], values[:1024], max_size=2097152).size, 1024)
|
||||
|
||||
def test_full_record_resolves_50_hz_at_high_sample_rate(self):
|
||||
times, values = self.sample(n=50000, fs=500000, frequencies=(50,), amplitude=.02)
|
||||
spectrum = self.core.analyze(times, values, max_size=4096, full_record=True)
|
||||
peak = self.core.dominant_peak(spectrum)
|
||||
self.assertAlmostEqual(spectrum.sample_rate / spectrum.size, 10., places=5)
|
||||
self.assertAlmostEqual(peak.frequency_hz, 50., delta=.2)
|
||||
self.assertAlmostEqual(peak.amplitude, .02, delta=.0002)
|
||||
self.assertEqual(len(times), 50000)
|
||||
broken = list(times)
|
||||
broken[100] = broken[99]
|
||||
with self.assertRaises(ValueError):
|
||||
self.core.analyze(broken, values, full_record=True)
|
||||
|
||||
def test_fft_matches_independent_direct_dft(self):
|
||||
times, _ = self.sample(32)
|
||||
values = [math.sin(i * 1.37) + 0.1 * i for i in range(32)]
|
||||
@@ -120,7 +140,7 @@ class SpectrumTests(unittest.TestCase):
|
||||
for n in (0, 1, 15):
|
||||
with self.assertRaisesRegex(ValueError, "16 samples"):
|
||||
self.core.analyze(times[:n], values[:n])
|
||||
for size in (0, 15, 1000, 32768):
|
||||
for size in (0, 15, 1000, 4194304):
|
||||
with self.assertRaises(ValueError):
|
||||
self.core.analyze(times, values, max_size=size)
|
||||
with self.assertRaises(ValueError):
|
||||
|
||||
Reference in New Issue
Block a user