Commit 459c7229 authored by Karol Hennessy's avatar Karol Hennessy

Merge branch 'gpl'

parents 302a5fef 7f4eaa77
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>.
MIT License
Copyright (c) 2020 HEV Collaboration, CERN
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
ansible_home=`pwd`/playbooks
export ANSIBLE_CONFIG=$ansible_home/ansible.cfg
export ANSIBLE_INVENTORY=$ansible_home/hosts
export ANSIBLE_LIBRARY=$ansible_home
......
---
- hosts: hevpi1
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
- hosts: hevpi
remote_user: pi
vars:
download_dir: /home/pi/Downloads
......
#!/bin/bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
download_dir=/home/pi/Downloads/
......
---
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
- hosts: hevpi
remote_user: pi
vars:
......
#!/bin/bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
sudo raspi-config nonint do_hostname hevpi
sudo raspi-config nonint do_overscan 1
......
---
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
- hosts: hevpi
remote_user: pi
vars:
......
#!/bin/bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
download_dir=/home/pi/Downloads
dev_dir=/home/pi/Development
......
#!/bin/bash
wget -qO - https://hev-sw.gitlab.io/public.key | sudo apt-key add - && echo deb https://hev-sw.gitlab.io/wip/deb/raspbian/ buster main | sudo tee /etc/apt/sources.list.d/hev-sw.list
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
---
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
- hosts: cernpi
remote_user: pi
vars:
......
---
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
- hosts: hevpi
remote_user: pi
vars:
......
rpi_swlist:
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
- vim
- cowsay
- openssh-server
......
#!/bin/bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
curl -fsSL https://raw.githubusercontent.com/platformio/platformio-core-installer/master/get-platformio.py -o get-platformio.py
python3 get-platformio.py
......
---
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
- hosts: allpi
remote_user: pi
vars:
......
---
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
- hosts: hevpi
remote_user: pi
vars:
......
#!/bin/bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
a2dismod wsgi
a2enmod wsgi
#update the locations in hev.conf if needed
......
#!/bin/bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
sketch=Multiloop_skeleton
......
- hosts: hevpi
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
vars:
download_dir: /home/pi/Downloads
......
int Sentor_P0 = A0;
void setup() {
// put your setup code here, to run once:
pinMode(2, OUTPUT);
pinMode(13, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(2, HIGH); // sets the digital pin 13 on
int P0 = analogRead(Sentor_P0);
delay(1000); // waits for a second
digitalWrite(2, LOW); // sets the digital pin 13 off
//Serial.print("P0");
Serial.println((String)+P0+",2000,");
/* Serial.println("1234");
Serial.println(P2);
Serial.println(P3);
Serial.println(P4);
(String)"x:"+x+" y:"+y
*/
;
// Serial.print("\n");
delay(1000);
}
import serial
import matplotlib.pyplot as plt
from drawnow import *
import atexit
P0 = []
P1 = []
x = []
plt.ion()
cnt=0
serialArduino = serial.Serial('/dev/ttyUSB0', 9600)
def plotValues():
plt.title('Serial value from Arduino')
plt.grid(True)
plt.ylabel('Pressure')
plt.plot(P0, 'rx-', label='P0')
plt.plot(P1, 'bx-', label='P1')
plt.legend(loc='upper right')
def doAtExit():
serialArduino.close()
print("Close serial")
print("serialArduino.isOpen() = " + str(serialArduino.isOpen()))
atexit.register(doAtExit)
print("serialArduino.isOpen() = " + str(serialArduino.isOpen()))
#pre-load dummy data
for i in range(0,26):
P0.append(0)
P1.append(0)
while True:
while (serialArduino.inWaiting()==0):
pass
print("readline()")
valueRead = serialArduino.readline()
print(valueRead)
#valueInInt = int(valueRead)
# x = valueRead.split()
# print(valueRead[1])
Pressure0 = valueRead.decode().split(",")[0]
print(Pressure0)
Pressure1 = valueRead.decode().split(",")[1]
print(Pressure1)
#check if valid value can be casted
try:
valueInInt = int(Pressure0)
valueInInt1 = int(Pressure1)
print(valueInInt)
if valueInInt <= 1024:
P0.append(valueInInt)
P0.pop(0)
P1.append(valueInInt1)
P1.pop(0)
drawnow(plotValues)
else:
print("Invalid! too large")
except ValueError:
print("Invalid! cannot cast")
"""
ldr.py
Display analog data from Arduino using Python (matplotlib)
Author: Mahesh Venkitachalam
Website: electronut.in
"""
import sys, serial, argparse
import numpy as np
from time import sleep
from collections import deque
import matplotlib.pyplot as plt
import matplotlib.animation as animation
# plot class
class AnalogPlot:
# constr
def __init__(self, strPort, maxLen):
# open serial port
self.ser = serial.Serial(strPort, 9600)
self.ax = deque([0.0]*maxLen)
self.ay = deque([0.0]*maxLen)
self.maxLen = maxLen
# add to buffer
def addToBuf(self, buf, val):
if len(buf) < self.maxLen:
buf.append(val)
else:
buf.pop()
buf.appendleft(val)
# add data
def add(self, data):
assert(len(data) == 2)
self.addToBuf(self.ax, data[0])
self.addToBuf(self.ay, data[1])
# update plot
def update(self, frameNum, a0, a1):
try:
line = self.ser.readline()
data = [float(val) for val in line.split()]
# print data
if(len(data) == 2):
self.add(data)
a0.set_data(range(self.maxLen), self.ax)
a1.set_data(range(self.maxLen), self.ay)
except KeyboardInterrupt:
print('exiting')
return a0,
# clean up
def close(self):
# close serial
self.ser.flush()
self.ser.close()
# main() function
def main():
# create parser
parser = argparse.ArgumentParser(description="LDR serial")
# add expected arguments
parser.add_argument('--port', dest='port', required=True)
# parse args
args = parser.parse_args()
#strPort = '/dev/tty.usbserial-A7006Yqh'
strPort = args.port
print('reading from serial port %s...' % strPort)
# plot parameters
analogPlot = AnalogPlot(strPort, 100)
print('plotting data...')
# set up animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 100), ylim=(0, 1023))
a0, = ax.plot([], [])
a1, = ax.plot([], [])
anim = animation.FuncAnimation(fig, analogPlot.update,
fargs=(a0, a1),
interval=50)
# show plot
plt.show()
# clean up
analogPlot.close()
print('exiting.')
# call main
if __name__ == '__main__':
main()
// Multi-loops skeleton
// Description: Shows 3 loops operating in "parallel" reading/writing a global variable
// Karol Hennessy
// 2020-03-29
#include <VariableTimedAction.h>
// global variables
static int globalcnt = 0;
class SafetyAlarmLoop : public VariableTimedAction
{
private:
int cnt = 0;
unsigned long run()
{
cnt++;
Serial.println("SA "+ String(globalcnt));
return 0;
}
public:
int getCnt()
{
return cnt;
}
} safetyalarmloop ;
class BreathingLoop : public VariableTimedAction
{
private:
int cnt = 0;
unsigned long run()
{
cnt++;
Serial.println("BR "+ String(cnt));
return 0;
}
public:
int getCnt()
{
return cnt;
}
} breathingloop;
class UILoop : public VariableTimedAction
{
private:
//int cnt = 0;
unsigned long run()
{
globalcnt++;
Serial.println("UI "+ String(globalcnt));
return 0;
}
public:
/* int getCnt()
{
return cnt;
}*/
} uiloop;
void setup() {
Serial.begin(9600);
// note - order is not guaranteed if they all run on the same "cycle"
safetyalarmloop.start(1000);
//breathingloop.start(500);
uiloop.start(1000);
}
void loop() {
// put your main code here, to run repeatedly:
VariableTimedAction::updateActions();
}
[env:uno]
platform = atmelavr
framework = arduino
board = uno
[env:mkrwifi1010]
platform = atmelsam
framework = arduino
board = mkrwifi1010
[env:mkrvidor4000]
platform = atmelsam
framework = arduino
board = mkrvidor4000
[env:featheresp32]
platform = espressif32
framework = arduino
board = featheresp32
[env:nodemcu-32s]
platform = espressif32
framework = arduino
board = nodemcu-32s
// Multi-loops skeleton
// Description: Shows 3 loops operating in "parallel" reading/writing a global variable
// Karol Hennessy
// 2020-03-29
#include <VariableTimedAction.h>
// global variables
static int globalcnt = 0;
class SafetyAlarmLoop : public VariableTimedAction
{
private:
int cnt = 0;
unsigned long run()
{
cnt++;
Serial.println("SA "+ String(globalcnt));
return 0;
}
public:
int getCnt()
{
return cnt;
}
} safetyalarmloop ;
class BreathingLoop : public VariableTimedAction
{
private:
int cnt = 0;
unsigned long run()
{
cnt++;
Serial.println("BR "+ String(cnt));
return 0;
}
public:
int getCnt()
{
return cnt;
}
} breathingloop;
class UILoop : public VariableTimedAction
{
private:
//int cnt = 0;
unsigned long run()
{
globalcnt++;
Serial.println("UI "+ String(globalcnt));
return 0;
}
public:
/* int getCnt()
{
return cnt;
}*/
} uiloop;
void setup() {
Serial.begin(9600);
// note - order is not guaranteed if they all run on the same "cycle"
safetyalarmloop.start(1000);
//breathingloop.start(500);
uiloop.start(1000);
}
void loop() {
// put your main code here, to run repeatedly:
VariableTimedAction::updateActions();
}
#include <LiquidCrystal.h>
//Arduino pins
const int rs = 7, en = 8, d4 = 9, d5 = 10, d6 = 11, d7 = 12;
LiquidCrystal lcd(rs, en, d4, d5, d6, d7);
void setup() {
lcd.begin(16, 2); // Declare number of columns and rows
Serial.begin(9600);
}
void loop() {
// This code shows on the LCD the characters received over serial port
if (Serial.available()) {
delay(1000);
lcd.clear();
while (Serial.available() > 0) {
lcd.write(Serial.read());
}
}
}
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env]
lib_deps =
5574 ; INA2xx
820 ; Adafruit mcp9808
[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
#include <Arduino.h>
#include <Wire.h>
#include <SPI.h>
#include "Adafruit_MCP9808.h"
#include <INA.h>
#define DEBUG
#ifdef DEBUG
#define DEBUG_SERIAL(x) Serial.begin (x)
#define DEBUG_PRINT(x) Serial.print (x)
#define DEBUG_PRINTLN(x) Serial.println (x)
#define DEBUG_PRINT2(x,y) Serial.print (x,y)
#define DEBUG_PRINTLN2(x,y) Serial.println (x,y)
#else
#define DEBUG_SERIAL(x)
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#define DEBUG_PRINT2(x,y)
#define DEBUG_PRINTLN2(x,y)
#endif
//Flag to close all valves of the system to stop the data taking in a safe state
bool stop = true;
// Create the MCP9808 temperature sensor object
Adafruit_MCP9808 tempsensor = Adafruit_MCP9808();
// Set Board to "ESP32 Dev Module"
// Set Port to /dev/ttyUSB0 on Linux
const int freq = 500; // 900 Hz for burkert 2875; Note - could be 500 Hz; depending on valve
float duty_cycle = 0.0;
const float max_duty_cycle = 0.85;
//const int pin_valve_air_in = 3; // RX0
const int pin_valve_o2_in = 5; // STRAPPING PIN (prefer as output / high-Z)
const int pin_valve_inhale = 21; // formerly valve_out
const int pin_valve_exhale = 19; // formerly valve_scavenge
const int pin_valve_purge = 18;
//const int pin_valve_atmosphere = 12; // A15 // STRAPPING PIN (prefer as output / high-Z)
const int pin_valve_air_in = 25; // DAC0
const int redled = 12; // red led on J28
const int yellowled = 16;
const int greenled = 17;
const int buzzer = 2;
const int p_patient = 32; // red led on J28
const int p_buffer = 34; //
const int p_air_supply = 36; //
const int p_air_regulated = 39; //
const int p_inhale = 35; //
const int p_o2_supply = 27; //
const int p_o2_regulated = 14; //
uint8_t devicesFound = 0; ///< Number of INAs found
INA_Class INA;
TwoWire I2CMCP9808 = TwoWire(0);
void setup() {
Serial.begin(9600);
//Wire.begin(SDA,SCL);
Wire.begin(22,23);
I2CMCP9808.begin(22,23);
if (!tempsensor.begin(0x18, &I2CMCP9808)) {
Serial.println("Couldn't find MCP9808! Check your connections and verify the address is correct.");
while (1);
}
tempsensor.setResolution(3);
// NodeMCU32
// pwm
ledcSetup(0, freq, 8);
ledcSetup(1, freq, 8);
//ledcSetup(1,2200,8); // buzzer frequency
//ledcAttachPin(pin_valve_o2_in , 0);
ledcAttachPin(pin_valve_inhale , 0);
ledcAttachPin(pin_valve_exhale , 1);
ledcAttachPin(buzzer , 1);
//ledcWrite(1, 128); //buzzer
pinMode(A13, INPUT); // potentiometer
// pressure sensors IO config
pinMode(p_patient, INPUT);
pinMode(p_buffer, INPUT);
pinMode(p_air_supply, INPUT);
pinMode(p_air_regulated, INPUT);
pinMode(p_inhale, INPUT);
pinMode(p_o2_supply, INPUT);
pinMode(p_o2_regulated, INPUT);
// Valves IO config
pinMode(pin_valve_air_in,OUTPUT);
//pinMode(pin_valve_exhale,OUTPUT);
pinMode(pin_valve_purge,OUTPUT);
pinMode(pin_valve_o2_in,OUTPUT);
// LEDs IO config
pinMode(redled,OUTPUT);
pinMode(yellowled,OUTPUT);
pinMode(greenled,OUTPUT);
if(stop){
//To Close all valves of the system
digitalWrite(pin_valve_air_in, LOW);
digitalWrite(pin_valve_exhale, LOW);
digitalWrite(pin_valve_purge, LOW);
digitalWrite(pin_valve_o2_in, LOW);
}
else{
//Default values for data taking
digitalWrite(pin_valve_air_in, HIGH);
//digitalWrite(pin_valve_exhale, LOW);
digitalWrite(pin_valve_purge, LOW);
digitalWrite(pin_valve_o2_in, HIGH);
}
//digitalWrite(redled, HIGH);
//digitalWrite(yellowled, HIGH);
//digitalWrite(greenled, HIGH);
DEBUG_PRINT("Hello");
Serial.println("Hello");
// current sensor configuration
devicesFound = INA.begin(1,500000); // Set to an expected 1 Amp maximum and a 100000 microOhm resistor
while (INA.begin(1, 500000) == 0)
{
DEBUG_PRINTLN("No INA device found, retrying in 10s...");
delay(1000); // Wait 10 seconds before retrying
} // while no devices detected
DEBUG_PRINT(" - Detected ");
DEBUG_PRINT(devicesFound);
DEBUG_PRINTLN(" INA devices on the I2C bus");
INA.setBusConversion(8500); // Maximum conversion time 8.244ms
INA.setShuntConversion(8500); // Maximum conversion time 8.244ms
INA.setAveraging(128); // Average each reading n-times
INA.setMode(INA_MODE_CONTINUOUS_BOTH); // Bus/shunt measured continuously
INA.AlertOnBusOverVoltage(true,5000); // Trigger alert if over 5V on bus
}
void loop() {
float res = analogRead(A13); //12 bit ADC on esp32
float pressure_patient = analogRead(p_patient); //12 bit ADC on esp32
float pressure_buffer = analogRead(p_buffer); //12 bit ADC on esp32
float pressure_asupply = analogRead(p_air_supply); //12 bit ADC on esp32
float pressure_aregulated = analogRead(p_air_regulated); //12 bit ADC on esp32
float pressure_inhale = analogRead(p_inhale); //12 bit ADC on esp32
float pressure_o2supply = analogRead(p_o2_supply); //12 bit ADC on esp32
float pressure_o2regulated = analogRead(p_o2_regulated); //12 bit ADC on esp32
tempsensor.wake(); //sensor on
float c = tempsensor.readTempC();
tempsensor.shutdown_wake(1); //sensor off
duty_cycle = res/4096.0;
if (duty_cycle > max_duty_cycle){
duty_cycle = max_duty_cycle;
}
//Serial.print("Pot ");
//Serial.print(String((int)res));
//Serial.print(" p_patient ");
//Serial.print(String((int)pressure_patient));
//Serial.print(" p_buffer ");
//Serial.print(String((int)pressure_buffer));
//Serial.print(" p_as ");
//Serial.print(String((int)pressure_asupply));
//Serial.print(" p_ar ");
//Serial.print(String((int)pressure_aregulated));
//Serial.print(" p_inhale ");
//Serial.print(String((int)pressure_inhale));
//Serial.print(" p_o2s ");
//Serial.print(String((int)pressure_o2supply));
//Serial.print(" p_o2r ");
//Serial.print(String((int)pressure_o2regulated));
//Serial.print(" Temp: ");
//Serial.print(c, 4);
//// measuring Valves voltage and current
//Serial.print(" ");
//Serial.print((float)INA.getBusMilliVolts(0)/1000.0,4);
//DEBUG_PRINT("V ");
//DEBUG_PRINT2((float)INA.getShuntMicroVolts(0)/5,0);
//DEBUG_PRINT("mA ");
//DEBUG_PRINT2((float)INA.getShuntMicroVolts(1)/5,0);
//DEBUG_PRINT("mA ");
//DEBUG_PRINT2((float)INA.getShuntMicroVolts(2)/5,0);
//DEBUG_PRINT("mA ");
//DEBUG_PRINT2((float)INA.getShuntMicroVolts(3)/5,0);
//DEBUG_PRINT("mA ");
if(stop){
ledcWrite(0, 0);//val);// exhale
ledcWrite(1, 0);//val);// exhale
}
else{
duty_cycle = 0.74;
float low_duty_cycle = 0.54;//525;
int nsteps = 1; // number of steps of 10 ms in between
float step_size = (duty_cycle-low_duty_cycle) / nsteps;
int val = (int)(255.0*duty_cycle);
int vallow = (int)(255.0*low_duty_cycle);
//Serial.print(" duty cycle ");
//Serial.println(String(duty_cycle));
//Serial.print(" raw val ");
//Serial.println(String(val));
digitalWrite(greenled, HIGH);
//ledcWrite(0, val);// inhale
ledcWrite(0, vallow);//vallow);// exhale
delay(1000);
for(int i=0; i<nsteps ; i++){
int _val = (int)( 255.0 * ( low_duty_cycle + ( i * step_size ) ) );
ledcWrite(0,_val);
delay(10);
}
ledcWrite(0, val);//val);// exhale
delay(1000);
//ledcWrite(1, 0);// exhale
//digitalWrite(greenled, LOW);
//delay(1000);
}
}
This directory is intended for PIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[platformio]
default_envs = uno
[env]
lib_deps =
commsControl
ArduinoQueue
uCRC16Lib
build_flags = -fpermissive -I../common/include/
[env:uno]
platform = atmelavr
framework = arduino
board = uno
[env:mkrvidor4000]
platform = atmelsam
framework = arduino
board = mkrvidor4000
[env:featheresp32]
platform = espressif32
framework = arduino
board = featheresp32
upload_port = /dev/ttyUSB0
[env:due]
platform = atmelsam
framework = arduino
board = due
[env:yun]
platform = atmelavr
framework = arduino
board = yun
[env:mkrwifi1010]
platform = atmelsam
framework = arduino
board = mkrwifi1010
[env:nodemcu-32s]
platform = espressif32
framework = arduino
board = nodemcu-32s
#include "common.h"
void setValves(bool vin, bool vout, bool vscav, bool vpurge)
{
digitalWrite(pin_valve_air_in, vin);
digitalWrite(pin_valve_o2_in, vin);
digitalWrite(pin_valve_inhale, vout);
digitalWrite(pin_valve_exhale, vscav);
digitalWrite(pin_valve_purge, vpurge);
}
#include <Arduino.h>
#if defined(ARDUINO_FEATHER_ESP32)
#define BOARD "HUZZAH32"
#include <huzzah32_pinout.h>
#elif defined(ARDUINO_NodeMCU_32S)
#define BOARD "ESP32"
#include <nodemcu_32s_pinout.h>
#elif defined(ARDUINO_AVR_UNO)
#define BOARD "UNO"
#include <Arduino_uno_pinout.h>
#elif defined(ARDUINO_SAMD_MKRVIDOR4000)
#define BOARD "VIDOR"
#include <Arduino_MKR_4000_Vidor_pinout.h>
#elif defined(ARDUINO_SAMD_MKRWIFI1010)
#define BOARD "MKR1010"
#include <Arduino_MKR_1010_WIFI_pinout.h>
#elif defined(ARDUINO_SAM_DUE)
#define BOARD "MKR1010"
#include <Arduino_Due_pinout.h>
#elif defined(ARDUINO_AVR_YUN)
#define BOARD "MKR1010"
#include <Arduino_Yun_pinout.h>
#endif
// input params
enum hev_modes : byte
{
HEV_MODE_PS,
HEV_MODE_CPAP,
HEV_MODE_PRVC,
HEV_MODE_TEST
};
enum valve_states : bool
{
V_OPEN = LOW,
V_CLOSED = HIGH
};
void setValves(bool vin, bool vout, bool vscav, bool vpurge);
#include <Arduino.h>
#include "test_hw_loop.h"
#include "common.h"
//#include <LiquidCrystal.h>
//LiquidCrystal lcd(pin_lcd_rs, pin_lcd_en, pin_lcd_d4, pin_lcd_d5, pin_lcd_d6, pin_lcd_d7);
int ventilation_mode = HEV_MODE_PS;
float working_pressure = 1; //?
float inspiratory_minute_volume = 6000; // ml/min
float respiratory_rate = 15; // 10-40 +-1 ;aka breaths_per_min
float inspiratory_pressure = 10; // 10-80 cmH2O +-1
//float tidal_volume = 200; // calc 200-1500ml +- 100
float inspiratory_time = 1.0; // 0.4-1.5s +-0.1
float pause_time = 1.0; // range?
//float expiratory_time ; // calc
float expiratory_minute_volume; // calc?? same as inspiratory_minute_volume?
float trigger_sensitivity;
// calculations
float calc_tidal_volume()
{
return inspiratory_minute_volume / respiratory_rate;
}
float calc_expiration_time()
{
float total_respiratory_time = 60.0 / respiratory_rate;
// total = expire + inspire + pause
return (total_respiratory_time - inspiratory_time - pause_time);
}
float calc_expiratory_minute_volume()
{
// probably need to calculate this from readings
return 0;
}
// FROM OVERLEAF DOC
// Working pressure, corresponding to the manually set and monitored input pressure to the unit
// Inspiratory Minute Volume setting
// Breaths per minute setting
// Tidal volume display, based on previous two parameters
// Inspiration time setting
// Pause time setting
// expiration time display based on previous two parameters
// expired minute volume
// Airway pressure display based on the reading of $P_2$ ??? not a setting
// PEEP setting ??? external
// Trigger sensitivity to patient initiated breath
void setup()
{
pinMode(pin_valve_air_in, OUTPUT);
pinMode(pin_valve_o2_in, OUTPUT);
pinMode(pin_valve_inhale, OUTPUT);
pinMode(pin_valve_exhale, OUTPUT);
pinMode(pin_valve_purge, OUTPUT);
pinMode(pin_p_air_supply, INPUT);
pinMode(pin_p_air_regulated, INPUT);
pinMode(pin_p_buffer, INPUT);
pinMode(pin_p_inhale, INPUT);
pinMode(pin_p_patient, INPUT);
pinMode(pin_temp, INPUT);
pinMode(pin_led_0, OUTPUT);
pinMode(pin_led_1, OUTPUT);
pinMode(pin_led_2, OUTPUT);
pinMode(pin_buzzer, OUTPUT);
pinMode(pin_button_0, INPUT);
Serial.begin(9600);
// lcd.begin(16, 2); // Declare number of columns and rows
}
void loop()
{
// put your main code here, to run repeatedly:
//Serial.println(BOARD);
// delay(1000);
// buzzer
// tone(pin, freq (Hz), duration);
//breath_cycle();
FSM_assignment();
FSM_breath_cycle();
delay(10);
}
#include "test_hw_loop.h"
#include "common.h"
/*
The Idea of this code is to unfold the FSM in two: one to assign the transitions and the second one to program the states.
*/
uint64_t FSM_time;
int timeout;
byte lab_cycle_mode = 0;
int bs_state = BS_IDLE;
bool start = LOW;
int next_state;
//This is used to assign the transitions of the fsm
void FSM_assignment( ) {
if (millis() > FSM_time + timeout ) {
switch (bs_state)
{
case BS_IDLE:
if (start == LOW)
{
next_state = BS_BUFF_PREFILL;
FSM_time = millis();
Serial.println("Exit IDLE") ;
}
else
{
next_state = BS_IDLE;
}
break;
case BS_BUFF_PREFILL:
next_state = BS_BUFF_FILL;
break;
case BS_BUFF_FILL:
next_state = BS_BUFF_LOADED;
break;
case BS_BUFF_LOADED:
switch (lab_cycle_mode)
{
case LAB_MODE_FLUSH:
next_state = BS_BUFF_FLUSH;
break;
case LAB_MODE_PURGE:
next_state = BS_BUFF_PURGE;
break;
default:
next_state = BS_BUFF_PRE_INHALE;
}
break;
case BS_BUFF_PRE_INHALE:
next_state = BS_INHALE;
break;
case BS_INHALE:
next_state = BS_PAUSE;
break;
case BS_PAUSE:
next_state = BS_EXHALE_FILL;
break;
case BS_EXHALE_FILL:
next_state = BS_EXHALE;
break;
case BS_EXHALE:
next_state = BS_BUFF_LOADED;
break;
case BS_BUFF_PURGE:
next_state = BS_BUFF_PREFILL;
break;
case BS_BUFF_FLUSH:
next_state = BS_IDLE;
break;
default:
next_state = bs_state;
}
bs_state = next_state;
FSM_time = millis();
}
}
void FSM_breath_cycle()
{
// basic cycle for testing hardware
start = digitalRead(pin_button_0);
switch (bs_state)
{
case BS_IDLE:
if (start == LOW)
{
FSM_time = millis();
}
else
{
timeout = 1000;
}
setValves(V_CLOSED, V_OPEN, V_OPEN, V_CLOSED);
break;
case BS_BUFF_PREFILL:
setValves(V_CLOSED, V_CLOSED, V_OPEN, V_CLOSED);
timeout = 1000;
break;
case BS_BUFF_FILL:
setValves(V_OPEN, V_CLOSED, V_OPEN, V_CLOSED);
timeout = 500;
break;
case BS_BUFF_LOADED:
setValves(V_CLOSED, V_CLOSED, V_OPEN, V_CLOSED);
switch (lab_cycle_mode)
{
case LAB_MODE_FLUSH:
timeout = 500;
break;
case LAB_MODE_PURGE:
timeout =500;
break;
default:
timeout =1500;
}
break;
case BS_BUFF_PRE_INHALE:
setValves(V_CLOSED, V_CLOSED, V_CLOSED, V_CLOSED);
timeout =100;
break;
case BS_INHALE:
setValves(V_CLOSED, V_OPEN, V_CLOSED, V_CLOSED);
timeout =100;
break;
case BS_PAUSE:
setValves(V_CLOSED, V_CLOSED, V_CLOSED, V_CLOSED);
timeout =1000;
break;
case BS_EXHALE_FILL:
setValves(V_OPEN, V_CLOSED, V_OPEN, V_CLOSED);
timeout =1000;
break;
case BS_EXHALE:
setValves(V_CLOSED, V_CLOSED, V_OPEN, V_CLOSED);
timeout =10;
break;
case BS_BUFF_PURGE:
setValves(V_CLOSED, V_CLOSED, V_OPEN, V_OPEN);
timeout =1000;
break;
case BS_BUFF_FLUSH:
setValves(V_CLOSED, V_OPEN, V_OPEN, V_CLOSED);
timeout =1000;
break;
}
Serial.println("state FSM_breath_cycle: " + String(bs_state));
Serial.println("start: " + String(start));
}
#include <Arduino.h>
void FSM_assignment();
void FSM_breath_cycle();
// states
enum BS_STATES : byte
{
BS_IDLE,
BS_BUFF_PREFILL,
BS_BUFF_FILL,
BS_BUFF_LOADED,
BS_BUFF_PRE_INHALE,
BS_INHALE,
BS_PAUSE,
BS_EXHALE_FILL,
BS_EXHALE,
BS_BUFF_PURGE,
BS_BUFF_FLUSH
};
enum lab_cycle_modes : byte
{
LAB_MODE_BREATHE = 0,
LAB_MODE_PURGE = 1,
LAB_MODE_FLUSH = 2
};
This directory is intended for PIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:nodemcu-32s]
platform = espressif32
board = nodemcu-32s
framework = arduino
#include <Arduino.h>
//#include <HardwareSerial.h>
HardwareSerial co2_serial(2); // RX2 = pin IO16, TX2 = pin IO17
// #define RXD2 16
// #define TXD2 17
unsigned char hexdata[9] = {0xFF, 0x01, 0x86, 0x00, 0x00, 0x00, 0x00, 0x00, 0x79}; //Read the gas density command /Don't change the order
void setup()
{
Serial.begin(9600);
while (!Serial)
{
delay(1);
}
Serial.println("setup Serial1 ok");
co2_serial.begin(9600);
// Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
// while (!Serial2)
while (!co2_serial)
{
delay(1);
}
Serial.println("setup Serial2 ok");
}
void loop()
{
co2_serial.write(hexdata, 9);
// delay(500);
// Serial2.write(hexdata, 9);
delay(500);
for (int i = 0, j = 0; i < 9; i++) {
if (co2_serial.available() > 0) {
// if (Serial2.available() > 0) {
long hi, lo, CO2;
int ch = co2_serial.read();
// int ch = Serial2.read();
if (i == 2) {
hi = ch;
} //High concentration
if (i == 3) {
lo = ch;
} //Low concentration
if (i == 8) {
CO2 = hi * 256 + lo; //CO2 concentration
Serial.print("CO2 concentration: ");
Serial.print(CO2);
Serial.println("ppm");
}
}
}
}
\ No newline at end of file
This directory is intended for PIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// Arduino Due
#define BOARD "DUE"
#define HEV_FULL_SYSTEM
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// Arduino MKR 1010 Wifi
#define BOARD "MKR1010"
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// arduino MKR 4000 Vidor
#define BOARD "VIDOR"
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// Arduino Nano 33 IOT
#define BOARD "NANO33IOT"
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// Arduino Yun
#define BOARD "YUN"
// pwm pins
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// Arduino Uno
#define BOARD "UNO"
// pwm pins
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// Arduino Uno
#define BOARD "UNO"
// pwm pins
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// ESP32 HUZZAH
#define BOARD "HUZZAH32"
#define CHIP_ESP32
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// Node MCU 32s
#define BOARD "NODEMCU32S"
#define CHIP_ESP32
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef COMMSCONSTANTS_H
#define COMMSCONSTANTS_H
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "CommsControl.h"
CommsControl::CommsControl(uint32_t baudrate) {
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef COMMS_CONTROL_H
#define COMMS_CONTROL_H
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "CommsFormat.h"
// constructor to init variables
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef COMMSFORMAT_H
#define COMMSFORMAT_H
......
.pio
.vscode/.browse.c_cpp.db*
.vscode/c_cpp_properties.json
.vscode/launch.json
.vscode/ipch
# Continuous Integration (CI) is the practice, in software
# engineering, of merging all developer working copies with a shared mainline
# several times a day < https://docs.platformio.org/page/ci/index.html >
#
# Documentation:
#
# * Travis CI Embedded Builds with PlatformIO
# < https://docs.travis-ci.com/user/integration/platformio/ >
#
# * PlatformIO integration with Travis CI
# < https://docs.platformio.org/page/ci/travis.html >
#
# * User Guide for `platformio ci` command
# < https://docs.platformio.org/page/userguide/cmd_ci.html >
#
#
# Please choose one of the following templates (proposed below) and uncomment
# it (remove "# " before each line) or use own configuration according to the
# Travis CI documentation (see above).
#
#
# Template #1: General project. Test it using existing `platformio.ini`.
#
# language: python
# python:
# - "2.7"
#
# sudo: false
# cache:
# directories:
# - "~/.platformio"
#
# install:
# - pip install -U platformio
# - platformio update
#
# script:
# - platformio run
#
# Template #2: The project is intended to be used as a library with examples.
#
# language: python
# python:
# - "2.7"
#
# sudo: false
# cache:
# directories:
# - "~/.platformio"
#
# env:
# - PLATFORMIO_CI_SRC=path/to/test/file.c
# - PLATFORMIO_CI_SRC=examples/file.ino
# - PLATFORMIO_CI_SRC=path/to/test/directory
#
# install:
# - pip install -U platformio
# - platformio update
#
# script:
# - platformio ci --lib="." --board=ID_1 --board=ID_2 --board=ID_N
{
// See http://go.microsoft.com/fwlink/?LinkId=827846
// for the documentation about the extensions.json format
"recommendations": [
"platformio.platformio-ide"
]
}
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[env:featheresp32]
platform = espressif32
framework = arduino
board = featheresp32
upload_port = /dev/ttyUSB0
; [env:nodemcu-32s]
; platform = espressif32
; framework = arduino
; board = nodemcu-32s
#include <Arduino.h>
#include <WiFi.h>
void setup() {
// put your setup code here, to run once:
// Huzzah32
// WiFi.mode(WIFI_MODE_NULL);
WiFi.mode(WIFI_OFF);
btStop();
// ADC2
pinMode(A0, INPUT);
pinMode(A1, INPUT);
pinMode(A5, INPUT);
pinMode(A12, INPUT);
pinMode(A11, INPUT);
pinMode(A10, INPUT);
pinMode(A8, INPUT);
pinMode(A6, INPUT);
// ADC1
pinMode(A2, INPUT);
pinMode(A3, INPUT);
pinMode(A4, INPUT);
pinMode(A9, INPUT);
pinMode(A7, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
int aA0 = analogRead(A0);
int aA1 = analogRead(A1);
int aA5 = analogRead(A5);
int aA12 = analogRead(A12);
int aA11 = analogRead(A11);
int aA10 = analogRead(A10);
int aA8 = analogRead(A8);
int aA6 = analogRead(A6);
int aA2 = analogRead(A2);
int aA3 = analogRead(A3);
int aA4 = analogRead(A4);
int aA9 = analogRead(A9);
int aA7 = analogRead(A7);
Serial.println("aA0 "+String(aA0));
Serial.println("aA1 "+String(aA1));
Serial.println("aA5 "+String(aA5));
Serial.println("aA12 "+String(aA12));
Serial.println("aA11 "+String(aA11));
Serial.println("aA10 "+String(aA10));
Serial.println("aA8 "+String(aA8 ));
Serial.println("aA6 "+String(aA6 ));
Serial.println("aA2 "+String(aA2 ));
Serial.println("aA3 "+String(aA3 ));
Serial.println("aA4 "+String(aA4 ));
Serial.println("aA9 "+String(aA9 ));
Serial.println("aA7 "+String(aA7 ));
delay(3000);
}
This directory is intended for PIO Unit Testing and project tests.
Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.
More information about PIO Unit Testing:
- https://docs.platformio.org/page/plus/unit-testing.html
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
Import("env")
# General options that are passed to the C and C++ compilers
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "AlarmLoop.h"
AlarmLoop::AlarmLoop()
......@@ -47,19 +70,32 @@ void AlarmLoop::fireAlarms() {
}
void AlarmLoop::updateValues(readings<float> fast_data, cycle_readings cr) {
_alarms.values[ALARM_CODES::CHECK_P_PATIENT] = static_cast<float>(fast_data.pressure_patient);
_alarms.values[ALARM_CODES::LOW_FIO2] = static_cast<float>(cr.fiO2_percent);
_alarms.values[ALARM_CODES::HIGH_FIO2] = static_cast<float>(cr.fiO2_percent);
_alarms.values[ALARM_CODES::APNEA] = static_cast<float>(cr.apnea_index);
_alarms.values[ALARM_CODES::HIGH_PRESSURE] = static_cast<float>(fast_data.pressure_patient);
_alarms.values[ALARM_CODES::HIGH_RR] = static_cast<float>(cr.respiratory_rate);
_alarms.values[ALARM_CODES::HIGH_VTE] = static_cast<float>(cr.exhaled_tidal_volume);
_alarms.values[ALARM_CODES::HIGH_VTI] = static_cast<float>(cr.inhaled_tidal_volume);
_alarms.values[ALARM_CODES::LOW_VTE] = static_cast<float>(cr.exhaled_tidal_volume);
_alarms.values[ALARM_CODES::LOW_VTI] = static_cast<float>(cr.inhaled_tidal_volume);
// _alarms.values[ALARM_CODES::LOW_PEEP] = static_cast<float>(cr.peep);
_alarms.values[ALARM_CODES::AIR_FAIL] = static_cast<float>(fast_data.pressure_air_regulated);
_alarms.values[ALARM_CODES::O2_FAIL] = static_cast<float>(fast_data.pressure_o2_regulated);
// ALARM_CODES::ALARM_CODE_UNKNOWN
setAlarm<float>(ALARM_CODES::APNEA , _alarms.values, static_cast<float>(cr.apnea_index));
// setAlarm<float>(ALARM_CODES::CHECK_VALVE_EXHALE , _alarms.values, );
setAlarm<float>(ALARM_CODES::CHECK_P_PATIENT , _alarms.values, static_cast<float>(fast_data.pressure_patient));
// setAlarm<float>(ALARM_CODES::EXPIRATION_SENSE_FAULT_OR_LEAK, _alarms.values, );
// setAlarm<float>(ALARM_CODES::EXPIRATION_VALVE_Leak , _alarms.values, );
setAlarm<float>(ALARM_CODES::HIGH_FIO2 , _alarms.values, static_cast<float>(cr.fiO2_percent));
setAlarm<float>(ALARM_CODES::HIGH_PRESSURE , _alarms.values, static_cast<float>(fast_data.pressure_patient));
setAlarm<float>(ALARM_CODES::HIGH_RR , _alarms.values, static_cast<float>(cr.respiratory_rate));
setAlarm<float>(ALARM_CODES::HIGH_VTE , _alarms.values, static_cast<float>(cr.exhaled_tidal_volume));
setAlarm<float>(ALARM_CODES::LOW_VTE , _alarms.values, static_cast<float>(cr.exhaled_tidal_volume));
setAlarm<float>(ALARM_CODES::HIGH_VTI , _alarms.values, static_cast<float>(cr.inhaled_tidal_volume));
setAlarm<float>(ALARM_CODES::LOW_VTI , _alarms.values, static_cast<float>(cr.inhaled_tidal_volume));
// setAlarm<float>(ALARM_CODES::INTENTIONAL_STOP , _alarms.values, );
// ALARM_CODES::LOW_BATTERY
setAlarm<float>(ALARM_CODES::LOW_FIO2 , _alarms.values, static_cast<float>(cr.fiO2_percent));
// setAlarm<float>(ALARM_CODES::OCCLUSION , _alarms.values, );
// setAlarm<float>(ALARM_CODES::HIGH_PEEP , _alarms.values, );
// setAlarm<float>(ALARM_CODES::LOW_PEEP , _alarms.values, static_cast<float>(cr.peep);
// ALARM_CODES::AC_POWER_DISCONNECTION
// ALARM_CODES::BATTERY_FAULT_SRVC
// ALARM_CODES::BATTERY_CHARGE
setAlarm<float>(ALARM_CODES::AIR_FAIL , _alarms.values, static_cast<float>(fast_data.pressure_air_regulated));
setAlarm<float>(ALARM_CODES::O2_FAIL , _alarms.values, static_cast<float>(fast_data.pressure_o2_regulated));
// setAlarm<float>(ALARM_CODES::PRESSURE_SENSOR_FAULT , _alarms.values, );
// setAlarm<float>(ALARM_CODES::ARDUINO_FAIL , _alarms.values, );
}
void AlarmLoop::setBatteryThresholds()
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef ALARM_LOOP_H
#define ALARM_LOOP_H
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "AudioVisualController.h"
#include "common.h"
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef AUDIOVISUALCONTROLLER_H
#define AUDIOVISUALCONTROLLER_H
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "BreathingLoop.h"
#include "common.h"
/*
......@@ -12,6 +35,8 @@ BreathingLoop::BreathingLoop()
_fsm_timeout = 1000;
_tsig_time = tnow;
_tsig_timeout = 100;
_calculations_time = tnow;
_calculations_timeout = 13;
_ventilation_mode = VENTILATION_MODE::PC_AC;
_bl_state = BL_STATES::IDLE;
......@@ -77,12 +102,17 @@ BreathingLoop::BreathingLoop()
_cycle_index = 0;
_min_inhale_time = 150;
_min_exhale_time = 300;
_min_exhale_time = 800;
_max_exhale_time = 10000; // for mandatory cycle - changed to 30s for the sponteneous breath testing
initTargets();
setVentilationMode(_ventilation_mode);
_o2_valve_frac = 0;
_expected_fiO2 = 0.21;
_new_expected_fiO2 = 0.21;
}
void BreathingLoop::initTargets()
......@@ -97,7 +127,7 @@ void BreathingLoop::initTargets()
_targets_pcac.peep = 5;
_targets_pcac.fiO2_percent = 21;
_targets_pcac.inhale_trigger_threshold = 1; // abs flow ? unit /
_targets_pcac.inhale_trigger_threshold = 5; // abs flow ? unit /
_targets_pcac.exhale_trigger_threshold = 0.25; // 25% of the peak flow
_targets_pcac.buffer_lower_pressure = 285.0;
......@@ -315,6 +345,20 @@ void BreathingLoop::updateCycleReadings()
}
void BreathingLoop::updateCalculations() {
uint32_t tnow = static_cast<uint32_t>(millis());
_calculations.flow = getFlow(); // TODO: can be run every 1 ms instead of every arduino cycle
if (tnow - _calculations_time >= _calculations_timeout) {
//_calculations.flow_calc = calculateFlow(_readings_avgs.timestamp, _readings_avgs.pressure_patient, _readings_avgs.pressure_buffer);
_calculations.flow_calc = calculateFlow(_readings_avgs.timestamp, _readings_avgs.pressure_patient, _readings_avgs.pressure_buffer);
_calculations_time = tnow;
}
// _calculations.flow_calc = calculateFlow(tnow, adcToMillibarFloat(_readings_raw.pressure_patient, _calib_avgs.pressure_patient), adcToMillibarFloat(_readings_raw.pressure_buffer, _calib_avgs.pressure_buffer));
_calculations.volume = getVolume();
_calculations.pressure_airway = getAirwayPressure();
}
void BreathingLoop::setVentilationMode(VENTILATION_MODE mode)
{
_ventilation_mode = mode;
......@@ -358,7 +402,7 @@ VENTILATION_MODE BreathingLoop::getVentilationMode() { return _ventilation_mode;
readings<float> BreathingLoop::getReadingAverages() { return _readings_avgs; }
readings<float> BreathingLoop::getRawReadings() { return _readings_raw; }
calculations<float> BreathingLoop::getCalculations() { return _calculations; }
float BreathingLoop::getPEEP()
{
......@@ -429,7 +473,7 @@ void BreathingLoop::FSM_assignment() {
next_state = BL_STATES::PAUSE;
break;
case BL_STATES::PAUSE:
next_state = BL_STATES::EXHALE;
next_state = BL_STATES::EXHALE;
break;
case BL_STATES::EXHALE:
if (_running == false) {
......@@ -499,6 +543,8 @@ void BreathingLoop::FSM_breathCycle()
bool mand_ex = false;
bool mand_vol = false;
float o2_frac_pressure = _o2_valve_frac * _targets_current->buffer_upper_pressure;
// basic cycle for testing hardware
switch (_bl_state) {
case BL_STATES::IDLE:
......@@ -589,22 +635,36 @@ void BreathingLoop::FSM_breathCycle()
//logMsg("pause "+String(_valley_flow_time)+" "+_measured_durations.inhale+ " "+_measured_durations.exhale+" " +_fsm_timeout);
_states_durations.exhale = calculateDurationExhale();
//logMsg("pause x "+String(_valley_flow_time)+" "+_measured_durations.inhale+ " "+_measured_durations.exhale+" " +_fsm_timeout +" "+_states_durations.exhale);
doO2ValveFrac(_targets_current->fiO2_percent, _targets_current->buffer_upper_pressure);
break;
case BL_STATES::EXHALE:
_peak_flow = -100000; // reset peak after inhale
_peak_flow_time = millis();
_fsm_timeout = _states_durations.exhale;
// uint32_t tnow = millis();
_expected_fiO2 = _new_expected_fiO2;
if(doExhalePurge()){
_valves_controller.setValves(VALVE_STATE::CLOSED, VALVE_STATE::CLOSED, VALVE_STATE::CLOSED, VALVE_STATE::OPEN, VALVE_STATE::OPEN);
// fill buffer to required pressure or timeout ; close valves 10ms before timeout.
if((_readings_avgs.pressure_buffer >= _targets_current->buffer_upper_pressure) || (millis() - _fsm_time >= (_fsm_timeout - 10))){
} else if((_readings_avgs.pressure_buffer >= _targets_current->buffer_upper_pressure) || (millis() - _fsm_time >= (_fsm_timeout - 10))){
_valves_controller.setValves(VALVE_STATE::CLOSED, VALVE_STATE::CLOSED, VALVE_STATE::CLOSED, VALVE_STATE::OPEN, VALVE_STATE::CLOSED);
} else if(_readings_avgs.pressure_buffer < _targets_current->buffer_lower_pressure){
_valves_controller.setValves(VALVE_STATE::OPEN, VALVE_STATE::OPEN, VALVE_STATE::CLOSED, VALVE_STATE::OPEN, VALVE_STATE::CLOSED);
if(_readings_avgs.pressure_buffer <= o2_frac_pressure ) {
// fill O2
_valves_controller.setValves(VALVE_STATE::CLOSED, VALVE_STATE::OPEN, VALVE_STATE::CLOSED, VALVE_STATE::OPEN, VALVE_STATE::CLOSED);
} else {
// fill AIR
_valves_controller.setValves(VALVE_STATE::OPEN, VALVE_STATE::CLOSED, VALVE_STATE::CLOSED, VALVE_STATE::OPEN, VALVE_STATE::CLOSED);
}
}
//logMsg("exhale "+String(_peak_flow_time)+" "+_measured_durations.inhale+ " "+_measured_durations.exhale+" " +_fsm_timeout);
measurePEEP();
digitalWrite(pin_led_red, LOW);
_mandatory_inhale = inhaleTrigger();
_pressure_buffer_fitter.resetCalculation(_peak_flow_time);
_pressure_patient_fitter.resetCalculation(_peak_flow_time);
break;
case BL_STATES::STANDBY:
_valves_controller.setValves(VALVE_STATE::CLOSED, VALVE_STATE::CLOSED, VALVE_STATE::CLOSED, VALVE_STATE::OPEN, VALVE_STATE::CLOSED);
......@@ -878,6 +938,23 @@ ValvesController* BreathingLoop::getValvesController()
// _total_cycle_duration[N-1] = newtotal;
// }
float BreathingLoop::calculateFlow(const uint32_t &current_time, const float &pressure_patient, const float &pressure_buffer, float volume_tube, float volume_buffer) {
float dp_tube, dp_buffer, offset;
uint8_t linreg;
float const_pressure = 1013.; //mbar
_pressure_buffer_fitter .appendPoints(current_time, pressure_buffer + const_pressure);
_pressure_patient_fitter.appendPoints(current_time, pressure_patient + const_pressure);
linreg = _pressure_buffer_fitter .linearRegression(dp_buffer, offset);
linreg += _pressure_patient_fitter.linearRegression(dp_tube , offset);
if (linreg == 0) return (((-1./(pressure_patient + const_pressure)) * ((dp_tube * volume_tube) + (dp_buffer * volume_buffer))));// - (1. * 4 * dp_tube));
//if (linreg == 0) return _pressure_buffer_fitter.GetSumX2(); //(((-1./(pressure_patient + const_pressure)) * ((dp_tube * volume_tube) + (dp_buffer * volume_buffer))));// - (1. * 4 * dp_tube));
else return 0;
//return dp_buffer;
}
float BreathingLoop::getFlow(){
const float temperature = 298.0;
const float pressure = 1030.0;
......@@ -1224,3 +1301,44 @@ void BreathingLoop::tsigReset()
}
}
void BreathingLoop::doO2ValveFrac(float desired_fiO2, float pressure_change)
{
// this assumes o2 and air valves fill at same rates, AND that we fill sequentially - o2, then air.
// pressure_change is proportional to the amount of volume exhanged in a cycle
// I think this equals tidal inhale volume
// we calculate amount of o2 : air to input
// if we have to fill 300 mbar, we fill up to (o2_frac * 300) mbar of o2, then (1-o2_frac)*300 mbar air
// we estimate the current o2 fraction, rather than wait for o2 sensor
// we should have an alarm if o2 sensor and o2 expectation is wrong after 1 min
float o2change = (desired_fiO2*(1000+pressure_change) - _expected_fiO2 *1000 -0.21*pressure_change)/(0.79*pressure_change);
if (o2change > 1){
o2change = 1;
} else if (o2change < 0){
o2change = 0;
}
_new_expected_fiO2 = _expected_fiO2*1000 + o2change*pressure_change + 0.21*(1-o2change)*pressure_change;
_o2_valve_frac = o2change;
// airValveFrac = 1.0 - O2ValveFrac
}
bool BreathingLoop::doExhalePurge()
{
// do nothing for now
return false;
uint32_t tnow = millis();
// purge-to-fill ratio = 0.66 => spend 66% time purging 33% filling buffer
if (tnow - _fsm_time >= static_cast<uint32_t>(0.66*_min_exhale_time) ) {
if (fabs(_targets_current->fiO2_percent - _readings_avgs.o2_percent) < 1) { // 1% tolerance
return true;
}
}
return false;
}
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef BREATHING_LOOP_H
#define BREATHING_LOOP_H
......@@ -30,8 +53,10 @@ public:
void updateReadings();
void updateRawReadings();
void updateCycleReadings();
void updateCalculations();
readings<float> getReadingAverages();
readings<float> getRawReadings();
calculations<float> getCalculations();
// float getRespiratoryRate();
float getTargetRespiratoryRate();
float getIERatio();
......@@ -50,6 +75,7 @@ public:
void setVentilationMode(VENTILATION_MODE mode);
VENTILATION_MODE getVentilationMode();
float calculateFlow(const uint32_t &current_time, const float &pressure_patient, const float &pressure_buffer, float volume_tube = 1600, float volume_buffer = 10000);
float getFlow();
float getVolume();
float getAirwayPressure();
......@@ -117,6 +143,9 @@ private:
states_durations _measured_durations = {0,0,0,0,0,0,0,0,0};
void measureDurations();
void measurePEEP();
void doO2ValveFrac(float desired_fiO2, float pressure_change);
bool doExhalePurge();
// targets
void initTargets();
target_variables _targets_pcac;
......@@ -130,6 +159,7 @@ private:
readings<float> _readings_sums; // 32 bit due to possible analog read overflow
readings<float> _readings_avgs;
readings<float> _readings_raw;
calculations<float> _calculations;
bool _readings_reset;
uint32_t _readings_N;
uint32_t _readings_time;
......@@ -140,6 +170,8 @@ private:
uint32_t _readings_cycle_timeout;
uint32_t _tsig_time;
uint32_t _tsig_timeout;
uint32_t _calculations_time;
uint32_t _calculations_timeout;
void tsigReset();
......@@ -177,6 +209,8 @@ private:
//float _pid_integral; // moved to pid_variable struct
LinearFitter _flow_fitter = LinearFitter(300, 100);
LinearFitter _pressure_buffer_fitter = LinearFitter(100,0);
LinearFitter _pressure_patient_fitter = LinearFitter(100,0);
// triggers
void runningAvgs();
bool inhaleTrigger();
......@@ -206,6 +240,10 @@ private:
uint32_t _min_exhale_time;
uint32_t _max_exhale_time;
float _o2_valve_frac;
float _expected_fiO2;
float _new_expected_fiO2;
};
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef LINEARFITTER_H
#define LINEARFITTER_H
......@@ -54,7 +77,7 @@ public:
uint8_t linearRegression(float &slope, float &offset) {
if (_x.isEmpty() || _y.isEmpty()) return 1;
if ((_x[_entries - 1] - _x[0]) < _duration ) return 2;
//if ((_x[_entries - 1] - _x[0]) < _duration ) return 2;
if ((_entries * _sum_x2) == (_sum_x * _sum_x)) return 3;
// results
......@@ -65,7 +88,7 @@ public:
float extrapolate(uint32_t x) {
x -= _x_zero;
float slope, offset;
uint8_t linreg = linearRegression(slope, offset);
uint8_t linreg = linearRegression(slope, offset);
if (0==linreg){
return (x*slope + offset);
}
......@@ -80,10 +103,16 @@ public:
y = _y[_entries-1] ;
entries = _entries;
}
uint16_t GetEntries(){
return _entries;
}
float GetSumX2(){
return _sum_x2;
}
private:
uint32_t _x_zero = 0;
uint8_t _entries = 0;
uint16_t _entries = 0;
uint32_t _duration = 0;
uint32_t _delay = 0;
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#if (ARDUINO >= 100)
#include <Arduino.h>
#else
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// MemoryFree library based on code posted here:
// http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1213583720/15
// Extended by Matthew Murdoch to include walking of the free list.
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "SystemUtils.h"
SystemUtils::SystemUtils()
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef SYSTEMUTILS_H
#define SYSTEMUTILS_H
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "UILoop.h"
UILoop::UILoop(BreathingLoop *bl, AlarmLoop *al, CommsControl *comms)
......@@ -105,9 +128,12 @@ void UILoop::reportFastReadings()
_fast_data.process_pressure = pid.process_pressure;
_fast_data.valve_duty_cycle = pid.valve_duty_cycle;
_fast_data.flow = _breathing_loop->getFlow();
_fast_data.volume= _breathing_loop->getVolume();
_fast_data.airway_pressure= _breathing_loop->getAirwayPressure();
calculations<float> calc = _breathing_loop->getCalculations();
_fast_data.flow = calc.flow;
_fast_data.flow_calc = calc.flow_calc;
_fast_data.volume = calc.volume;
_fast_data.airway_pressure = calc.pressure_airway;
_pl_send.setPayload(PRIORITY::DATA_ADDR, reinterpret_cast<void *>(&_fast_data), sizeof(_fast_data));
_comms->writePayload(_pl_send);
......@@ -147,7 +173,7 @@ void UILoop::reportReadbackValues()
_readback_data.valve_exhale = vexhale;
_readback_data.valve_purge = vpurge;
_readback_data.ventilation_mode = static_cast<uint8_t>(_breathing_loop->getVentilationMode());
_readback_data.ventilation_mode = _breathing_loop->getVentilationMode();
_readback_data.valve_inhale_percent = 0;
_readback_data.valve_exhale_percent = 0;
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef UI_LOOP_H
#define UI_LOOP_H
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "ValvesController.h"
ValvesController::ValvesController()
......@@ -49,7 +72,7 @@ ValvesController::ValvesController()
_valve_params.inhale_duty_cycle = 0;
_valve_params.inhale_open_max = MAX_VALVE_FRAC_OPEN;
_valve_params.inhale_open_min = 0.53;
_valve_params.inhale_open_min = 0.51;
_valve_params.valve_air_in_enable = 1;
_valve_params.valve_o2_in_enable = 1;
_valve_params.valve_purge_enable = 1;
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef VALVES_CONTROLLER_H
#define VALVES_CONTROLLER_H
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include "common.h"
CommsControl* global_comms;
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef COMMON_H
#define COMMON_H
#include <Arduino.h>
......@@ -229,6 +252,7 @@ struct fast_data_format {
uint16_t ambient_temperature = 0;
float airway_pressure = 0.0;
float flow = 0.0;
float flow_calc = 0.0;
float volume = 0.0;
float target_pressure = 0.0; //
float process_pressure = 0.0;
......@@ -664,6 +688,15 @@ template <typename T> struct readings{
T o2_percent = 0;
};
template <typename T> struct calculations {
uint32_t timestamp = 0;
T flow = 0;
T flow_calc = 0;
T volume = 0;
T pressure_airway = 0;
};
template <typename T> struct IV_readings{
uint64_t timestamp = 0; //
T inhale_current = 0;
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#ifndef LOCALCONF_H
#define LOCALCONF_H
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
#include <Arduino.h>
#include "common.h"
#ifdef CHIP_ESP32
......@@ -138,6 +161,7 @@ void loop()
breathing_loop.updateReadings();
breathing_loop.updateRawReadings();
breathing_loop.updateCycleReadings();
breathing_loop.updateCalculations();
// update alarm values
// TODO assign more values
alarm_loop.updateValues(breathing_loop.getReadingAverages(), breathing_loop.getCycleReadings());
......
#!/usr/bin/python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# from Oscar's excel sheet
......
This directory is intended for project header files.
A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.
```src/main.c
#include "header.h"
int main (void)
{
...
}
```
Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.
In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.
Read more about using header files in official GCC documentation:
* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes
https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.
The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").
For example, see a structure of the following two libraries `Foo` and `Bar`:
|--lib
| |
| |--Bar
| | |--docs
| | |--examples
| | |--src
| | |- Bar.c
| | |- Bar.h
| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
| |
| |--Foo
| | |- Foo.c
| | |- Foo.h
| |
| |- README --> THIS FILE
|
|- platformio.ini
|--src
|- main.c
and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>
int main (void)
{
...
}
```
PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.
More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
; PlatformIO Project Configuration File
;
; Build options: build flags, source filter
; Upload options: custom upload port, speed and extra flags
; Library options: dependencies, extra library storages
; Advanced options: extra scripting
;
; Please visit documentation for the other options and examples
; https://docs.platformio.org/page/projectconf.html
[platformio]
default_envs = uno
[env]
lib_deps =
commsControl
5390 ; uCRC16Lib
5418 ; RingBuffer
build_flags = -fpermissive -I../common/include/
lib_extra_dirs = ../common/lib
[env:uno]
platform = atmelavr
framework = arduino
board = uno
[env:mkrvidor4000]
platform = atmelsam
framework = arduino
board = mkrvidor4000
[env:featheresp32]
platform = espressif32
framework = arduino
board = featheresp32
upload_port = /dev/ttyUSB0
[env:due]
platform = atmelsam
framework = arduino
board = due
[env:yun]
platform = atmelavr
framework = arduino
board = yun
;[env:mkrwifi1010]
;platform = atmelsam
;framework = arduino
;board = mkrwifi1010
[env:nodemcu-32s]
platform = espressif32
framework = arduino
board = nodemcu-32s
win32 {
HOMEDIR += $$(USERPROFILE)
}
else {
HOMEDIR += $$(HOME)
}
INCLUDEPATH += "$${_PRO_FILE_PWD_}/include"
INCLUDEPATH += "$${_PRO_FILE_PWD_}/src"
INCLUDEPATH += "$${_PRO_FILE_PWD_}/../common/lib/commsControl"
INCLUDEPATH += "$${_PRO_FILE_PWD_}/.pio/libdeps/uno/uCRC16Lib_ID5390/src"
INCLUDEPATH += "$${_PRO_FILE_PWD_}/.pio/libdeps/uno/RingBuffer_ID5418/src"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/framework-arduino-avr/cores/arduino"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/framework-arduino-avr/variants/standard"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/framework-arduino-avr/libraries/EEPROM/src"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/framework-arduino-avr/libraries/HID/src"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/framework-arduino-avr/libraries/SPI/src"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/framework-arduino-avr/libraries/SoftwareSerial/src"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/framework-arduino-avr/libraries/Wire/src"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/toolchain-atmelavr/avr/include"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/toolchain-atmelavr/lib/gcc/avr/5.4.0/include"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/toolchain-atmelavr/lib/gcc/avr/5.4.0/include-fixed"
INCLUDEPATH += "$${HOMEDIR}/.platformio/packages/tool-unity"
DEFINES += "PLATFORMIO=40301"
DEFINES += "ARDUINO_AVR_UNO"
DEFINES += "F_CPU=16000000L"
DEFINES += "ARDUINO_ARCH_AVR"
DEFINES += "ARDUINO=10808"
DEFINES += "__AVR_ATmega328P__"
OTHER_FILES += platformio.ini
SOURCES += src/protocol.cpp \
../common/lib/commsControl/commsControl.cpp \
../common/lib/commsControl/commsFormat.cpp
HEADERS += ../common/lib/commsControl/commsConstants.h \
../common/lib/commsControl/commsControl.h \
../common/lib/commsControl/commsFormat.h
#include <Arduino.h>
#include "commsControl.h"
#define LED_BLUE 5
#define LED_GREEN 7
#define LED_RED 3
#define BTN 8
payload plReceive_;
payload plSend_;
commsControl comms_;
dataFormat data_;
alarmFormat alarm_;
int currentState_ = 0;
int previousState_ = 0;
int led_ = 0;
bool blue_ = false;
bool green_ = false;
bool red_ = false;
bool enabled_ = false;
uint32_t lastTime_ = 0;
uint32_t offset_ = 10;
// dirty function to switch one of the LEDs
void switchLED(int led) {
int state = HIGH;
switch (led) {
case LED_BLUE:
if (blue_)
state = LOW;
blue_ = !blue_;
break;
case LED_RED:
if (red_)
state = LOW;
red_ = !red_;
break;
case LED_GREEN:
if (green_)
state = LOW;
green_ = !green_;
break;
}
digitalWrite(led, state);
}
void setup() {
plSend_.setType(payloadType::payloadData);
// initialize digital pin LED_BUILTIN as an output.
pinMode(LED_BLUE, OUTPUT);
pinMode(LED_GREEN, OUTPUT);
pinMode(LED_RED, OUTPUT);
pinMode(BTN, INPUT);
// initialize comms connection
comms_.beginSerial();
}
void loop() {
// testing increase of values to be sent
// will only increase the count on the button release (reasons)
currentState_ = digitalRead(BTN);
if ( currentState_ != previousState_) {
if (currentState_ != HIGH) {
switchLED(LED_BLUE);
// counter increase on button press
data_.fsm_state += 1;
plSend_.setData(&data_);
// register new data in comms
comms_.writePayload(plSend_);
}
previousState_ = currentState_;
}
if (enabled_ & (millis() > (lastTime_ + offset_)))
{
lastTime_ = millis();
plSend_.getData()->readback_valve_air_in = static_cast<uint8_t>((lastTime_ >> 24) & 0xFF);
plSend_.getData()->readback_valve_o2_in = static_cast<uint8_t>((lastTime_ >> 16) & 0xFF);
plSend_.getData()->readback_valve_inhale = static_cast<uint8_t>((lastTime_ >> 8 ) & 0xFF);
plSend_.getData()->readback_valve_exhale = static_cast<uint8_t>((lastTime_ >> 0 ) & 0xFF);
switchLED(LED_BLUE);
plSend_.setType(payloadType::payloadData);
plSend_.getData()->fsm_state += 1;
comms_.writePayload(plSend_);
}
// per cycle sender
comms_.sender();
// per cycle receiver
int x1, x2, x3 = 0;
comms_.receiver(x1,x2,x3);
if (comms_.readPayload(plReceive_)) {
switch (plReceive_.getType()) {
case payloadType::payloadCmd:
if (plReceive_.getCmd()->cmdCode % 2 == 0) {
enabled_ = false;
} else {
enabled_ = true;
}
offset_ = plReceive_.getCmd()->param;
alarm_.alarmCode = plReceive_.getCmd()->cmdCode;
alarm_.param = millis() & 0xFFFFFFFF;
plSend_.setAlarm(&alarm_);
comms_.writePayload(plSend_);
break;
default:
break;
}
plReceive_.setType(payloadType::payloadUnset);
}
}
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import asyncio
import logging
......
../raspberry-dataserver/CommsCommon.py
\ No newline at end of file
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from struct import Struct
from enum import Enum, IntEnum, auto, unique
from dataclasses import dataclass, asdict, field, fields
from typing import Any, ClassVar, Dict
import logging
import binascii
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# VERSIONING
# change version in PayloadFormat for all data
# i.e. if and of DataFormat, CommandFormat or AlarmFormat change
# then change the RPI_VERSION
# =======================================
# Enum definitions
# =======================================
@unique
class CMD_TYPE(Enum):
GENERAL = 1
SET_DURATION = 2
SET_MODE = 3
SET_THRESHOLD_MIN = 4
SET_THRESHOLD_MAX = 5
SET_VALVE = 6
SET_PID = 7
SET_TARGET_PC_AC = 8
SET_TARGET_PC_AC_PRVC = 9
SET_TARGET_PC_PSV = 10
SET_TARGET_CPAP = 11
SET_TARGET_TEST = 12
SET_TARGET_CURRENT = 13
GET_TARGETS = 14
SET_PERSONAL = 15
GET_THRESHOLD_MIN = 16
GET_THRESHOLD_MAX = 17
@unique
class CMD_GENERAL(Enum):
START = 1
STOP = 2
RESET = 3
STANDBY = 4
GET_PERSONAL = 5
# Taken from the FSM doc. Correct as of 1400 on 20200417
@unique
class CMD_SET_DURATION(Enum):
PRE_CALIBRATION = 1
CALIBRATION = 2
BUFF_PURGE = 3
BUFF_FLUSH = 4
BUFF_PREFILL = 5
BUFF_FILL = 6
BUFF_PRE_INHALE = 7
INHALE = 8
PAUSE = 9
EXHALE = 10
@unique
class VENTILATION_MODE(Enum):
UNKNOWN = 0
PC_AC = 1
PC_AC_PRVC = 2
PC_PSV = 3
CPAP = 4
TEST = 5
PURGE = 6
FLUSH = 7
CURRENT = 100 # not settable
@unique
class CMD_SET_VALVE(Enum):
AIR_IN_ENABLE = 1
O2_IN_ENABLE = 2
PURGE_ENABLE = 3
INHALE_DUTY_CYCLE = 4
INHALE_OPEN_MIN = 5
INHALE_OPEN_MAX = 6
INHALE_TRIGGER_ENABLE = 7
EXHALE_TRIGGER_ENABLE = 8
@unique
class CMD_SET_PID(Enum):
KP = 1
KI = 2
KD = 3
PID_GAIN = 4
TARGET_FINAL_PRESSURE = 5
NSTEPS = 6
MAX_PATIENT_PRESSURE = 7
@unique
class CMD_SET_TARGET(Enum):
INSPIRATORY_PRESSURE = 1
RESPIRATORY_RATE = 2
IE_RATIO = 3
VOLUME = 4
PEEP = 5
FIO2_PERCENT = 6
INHALE_TIME = 7
INHALE_TRIGGER_THRESHOLD = 8
EXHALE_TRIGGER_THRESHOLD = 9
#PID_GAIN = 10
# for debugging only; not for UIs
INHALE_TRIGGER_ENABLE = 11
EXHALE_TRIGGER_ENABLE = 12
VOLUME_TRIGGER_ENABLE = 13
@unique
# class CMD_SET_PERSONAL(Enum):
# NAME = 1
# AGE = 2
# SEX = 3
# HEIGHT = 4
# WEIGHT = 5
@unique
class ALARM_TYPE(Enum):
PRIORITY_LOW = 1
PRIORITY_MEDIUM = 2
PRIORITY_HIGH = 3
@unique
class ALARM_CODES(Enum):
UNKNOWN = 0
APNEA = 1 # HP
CHECK_VALVE_EXHALE = 2 # HP
CHECK_P_PATIENT = 3 # HP
EXPIRATION_SENSE_FAULT_OR_LEAK = 4 # MP
EXPIRATION_VALVE_LEAK = 5 # MP
HIGH_FIO2 = 6 # MP
HIGH_PRESSURE = 7 # HP
HIGH_RR = 8 # MP
HIGH_VTE = 9 # MP
LOW_VTE = 10 # MP
HIGH_VTI = 11 # MP
LOW_VTI = 12 # MP
INTENTIONAL_STOP = 13 # HP
LOW_BATTERY = 14 # HP (LP) if AC power isn't (is) connected
LOW_FIO2 = 15 # HP
OCCLUSION = 16 # HP
HIGH_PEEP = 17 # HP
LOW_PEEP = 18 # HP
AC_POWER_DISCONNECTION = 19 # MP
BATTERY_FAULT_SRVC = 20 # MP
BATTERY_CHARGE = 21 # MP
AIR_FAIL = 22 # HP
O2_FAIL = 23 # HP
PRESSURE_SENSOR_FAULT = 24 # HP
ARDUINO_FAIL = 25 # HP
class CMD_MAP(Enum):
GENERAL = CMD_GENERAL
SET_DURATION = CMD_SET_DURATION
SET_MODE = VENTILATION_MODE
SET_VALVE = CMD_SET_VALVE
SET_PID = CMD_SET_PID
SET_TARGET_PC_AC = CMD_SET_TARGET
SET_TARGET_PC_AC_PRVC = CMD_SET_TARGET
SET_TARGET_PC_PSV = CMD_SET_TARGET
SET_TARGET_CPAP = CMD_SET_TARGET
SET_TARGET_TEST = CMD_SET_TARGET
SET_TARGET_CURRENT = CMD_SET_TARGET
SET_THRESHOLD_MIN = ALARM_CODES
SET_THRESHOLD_MAX = ALARM_CODES
GET_THRESHOLD_MIN = ALARM_CODES
GET_THRESHOLD_MAX = ALARM_CODES
GET_TARGETS = VENTILATION_MODE
# SET_PERSONAL = CMD_SET_PERSONAL
@unique
class BL_STATES(Enum):
UNKNOWN = 0
IDLE = 1
PRE_CALIBRATION = 2
CALIBRATION = 3
BUFF_PREFILL = 4
BUFF_FILL = 5
BUFF_PRE_INHALE = 6
INHALE = 7
PAUSE = 8
EXHALE = 9
STOP = 10
BUFF_PURGE = 11
BUFF_FLUSH = 12
STANDBY = 13
@unique
class PAYLOAD_TYPE(IntEnum):
UNSET = 0
DATA = 1
READBACK = 2
CYCLE = 3
THRESHOLDS = 4
CMD = 5
ALARM = 6
DEBUG = 7
IVT = 8
LOGMSG = 9
TARGET = 10
BATTERY = 11
LOOP_STATUS = 12
PERSONAL = 13
class HEVVersionError(Exception):
pass
@dataclass
class PayloadFormat():
# class variables excluded from init args and output dict
_RPI_VERSION: ClassVar[int] = field(default=0xB6, init=False, repr=False)
_dataStruct: ClassVar[Any] = field(default=Struct("<BIB"), init=False, repr=False)
_byteArray: ClassVar[bytearray] = field(default=None, init=False, repr=False)
# Meta information
version: int = 0
timestamp: int = 0
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.UNSET
@classmethod
def fromByteArray(cls, rec_bytes):
"""Automatically determine which subclass to initialise as"""
DATA_TYPE_TO_CLASS = {
1: DataFormat,
2: ReadbackFormat,
3: CycleFormat,
#4: ThresholdFormat,
5: CommandFormat,
6: AlarmFormat,
7: DebugFormat,
8: IVTFormat,
9: LogMsgFormat,
10: TargetFormat,
11: BatteryFormat,
12: LoopStatusFormat,
13: PersonalFormat
}
ReturnType = DATA_TYPE_TO_CLASS[rec_bytes[5]]
payload_obj = ReturnType()
payload_obj.fromByteArray(rec_bytes)
return payload_obj
@property
def byteArray(self) -> bytearray:
self.toByteArray()
return self._byteArray
@byteArray.setter
def byteArray(self, byte_array) -> None:
self._byteArray = byte_array
def toByteArray(self) -> None:
self.version = self._RPI_VERSION
self._byteArray = self._dataStruct.pack(*[
v.value if isinstance(v, IntEnum) or isinstance(v, Enum) else v
for v in asdict(self).values()
])
# check for mismatch between pi and microcontroller version
def checkVersion(self):
if self._RPI_VERSION != self.version :
raise HEVVersionError('Version Mismatch', "PI:", self._RPI_VERSION, "uC:", self.version)
def getSize(self) -> int:
return len(self.byteArray)
def getType(self) -> Any:
return self.payload_type if isinstance(self.payload_type, IntEnum) else PAYLOAD_TYPE(self.payload_type)
def getDict(self) -> Dict:
return {k: v.name if isinstance(v, IntEnum) or isinstance(v, Enum) else v for k, v in asdict(self).items()}
# =======================================
# fast data payload
# =======================================
@dataclass
class DataFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBBHfHffffHfHHffffffffff")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.DATA
# subclass member variables
fsm_state: BL_STATES = BL_STATES.IDLE
pressure_air_supply: int = 0
pressure_air_regulated: float = 0.0
pressure_o2_supply: int = 0
pressure_o2_regulated: float = 0.0
pressure_buffer: float = 0.0
pressure_inhale: float = 0.0
pressure_patient: float = 0.0
temperature_buffer: int = 0
pressure_diff_patient: float = 0.0
ambient_pressure: int = 0
ambient_temperature: int = 0
airway_pressure: float = 0.0
flow: float = 0.0
flow_calc : float = 0.0
volume : float = 0.0
target_pressure : float = 0.0 ##
process_pressure: float = 0.0
valve_duty_cycle: float = 0.0
proportional : float = 0.0
integral : float = 0.0 ##
derivative : float = 0.0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_state = 0
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
tmp_state,
self.pressure_air_supply,
self.pressure_air_regulated,
self.pressure_o2_supply,
self.pressure_o2_regulated,
self.pressure_buffer,
self.pressure_inhale,
self.pressure_patient,
self.temperature_buffer,
self.pressure_diff_patient,
self.ambient_pressure,
self.ambient_temperature,
self.airway_pressure,
self.flow,
self.flow_calc,
self.volume,
self.target_pressure ,
self.process_pressure,
self.valve_duty_cycle,
self.proportional ,
self.integral ,
self.derivative
) = self._dataStruct.unpack(byteArray)
self.fsm_state = BL_STATES(tmp_state)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# readback data payload
# =======================================
@dataclass
class ReadbackFormat(PayloadFormat):
_dataStruct = Struct("<BIBHHHHHHHHHHffBBBBBBBBBBBffffffB")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.READBACK
duration_pre_calibration: int = 0
duration_calibration: int = 0
duration_buff_purge: int = 0
duration_buff_flush: int = 0
duration_buff_prefill: int = 0
duration_buff_fill: int = 0
duration_buff_pre_inhale: int = 0
duration_inhale: int = 0
duration_pause: int = 0
duration_exhale: int = 0
valve_air_in: float = 0.0
valve_o2_in: float = 0.0
valve_inhale: int = 0
valve_exhale: int = 0
valve_purge: int = 0
ventilation_mode: int = VENTILATION_MODE.PC_AC
valve_inhale_percent: int = 0
valve_exhale_percent: int = 0
valve_air_in_enable: int = 0
valve_o2_in_enable: int = 0
valve_purge_enable: int = 0
inhale_trigger_enable: int = 0
exhale_trigger_enable: int = 0
peep: float = 0.0
inhale_exhale_ratio: float = 0.0
kp : float = 0.0
ki : float = 0.0
kd : float = 0.0
pid_gain : float = 0.0
max_patient_pressure : int = 0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_mode = 0
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.duration_pre_calibration,
self.duration_calibration,
self.duration_buff_purge,
self.duration_buff_flush,
self.duration_buff_prefill,
self.duration_buff_fill,
self.duration_buff_pre_inhale,
self.duration_inhale,
self.duration_pause,
self.duration_exhale,
self.valve_air_in,
self.valve_o2_in,
self.valve_inhale,
self.valve_exhale,
self.valve_purge,
tmp_mode,
self.valve_inhale_percent,
self.valve_exhale_percent,
self.valve_air_in_enable,
self.valve_o2_in_enable,
self.valve_purge_enable,
self.inhale_trigger_enable,
self.exhale_trigger_enable,
self.peep,
self.inhale_exhale_ratio,
self.kp ,
self.ki ,
self.kd ,
self.pid_gain ,
self.max_patient_pressure
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.ventilation_mode = VENTILATION_MODE(tmp_mode)
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# cycle data payload
# =======================================
@dataclass
class CycleFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBffffffffffffffHHB")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.CYCLE
respiratory_rate: float = 0.0
tidal_volume: float = 0.0
exhaled_tidal_volume: float = 0.0
inhaled_tidal_volume: float = 0.0
minute_volume: float = 0.0
exhaled_minute_volume: float = 0.0
inhaled_minute_volume: float = 0.0
lung_compliance: float = 0.0
static_compliance: float = 0.0
inhalation_pressure: float = 0.0
peak_inspiratory_pressure: float = 0.0
plateau_pressure: float = 0.0
mean_airway_pressure: float = 0.0
fiO2_percent: float = 0.0
apnea_index: int = 0
apnea_time: int = 0
mandatory_breath: int = 0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.respiratory_rate,
self.tidal_volume,
self.exhaled_tidal_volume,
self.inhaled_tidal_volume,
self.minute_volume,
self.exhaled_minute_volume,
self.inhaled_minute_volume,
self.lung_compliance,
self.static_compliance,
self.inhalation_pressure,
self.peak_inspiratory_pressure,
self.plateau_pressure,
self.mean_airway_pressure,
self.fiO2_percent,
self.apnea_index,
self.apnea_time,
self.mandatory_breath) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# debug data payload; this can change
# =======================================
@dataclass
class DebugFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBfffffffff")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.DEBUG
kp : float = 0.0
ki : float = 0.0
kd : float = 0.0
target_pressure : float = 0.0 ##
process_pressure: float = 0.0
valve_duty_cycle: float = 0.0
proportional : float = 0.0
integral : float = 0.0 ##
derivative : float = 0.0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.kp ,
self.ki ,
self.kd ,
self.target_pressure ,
self.process_pressure,
self.valve_duty_cycle,
self.proportional ,
self.integral ,
self.derivative
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# debug data payload; this can change
# =======================================
@dataclass
class LoopStatusFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBffIIBBB")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.LOOP_STATUS
duration_loop : float = 0.0
duration_loop_max : float = 0.0
dropped_send : int = 0
dropped_receive : int = 0
buffer_alarm : int = 0
buffer_cmd : int = 0
buffer_data : int = 0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.duration_loop ,
self.duration_loop_max,
self.dropped_send ,
self.dropped_receive ,
self.buffer_alarm ,
self.buffer_cmd ,
self.buffer_data ,
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# thresholds eata payload
# =======================================
# TODO
# =======================================
# IVT data payload
# =======================================
@dataclass
class IVTFormat(PayloadFormat):
_dataStruct = Struct("<BIBffffffffffBBBBBf")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.IVT
inhale_current : float = 0.0
exhale_current : float = 0.0
purge_current : float = 0.0
air_in_current : float = 0.0
o2_in_current : float = 0.0
inhale_voltage : float = 0.0
exhale_voltage : float = 0.0
purge_voltage : float = 0.0
air_in_voltage : float = 0.0
o2_in_voltage : float = 0.0
inhale_i2caddr : int = 0.0
exhale_i2caddr : int = 0.0
purge_i2caddr : int = 0.0
air_in_i2caddr : int = 0.0
o2_in_i2caddr : int = 0.0
system_temp : float = 0.0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.inhale_current ,
self.exhale_current ,
self.purge_current ,
self.air_in_current ,
self.o2_in_current ,
self.inhale_voltage ,
self.exhale_voltage ,
self.purge_voltage ,
self.air_in_voltage ,
self.o2_in_voltage ,
self.inhale_i2caddr ,
self.exhale_i2caddr ,
self.purge_i2caddr ,
self.air_in_i2caddr ,
self.o2_in_i2caddr ,
self.system_temp
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# Target data payload
# =======================================
@dataclass
class TargetFormat(PayloadFormat):
_dataStruct = Struct("<BIBBfffffffBBBffff")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.TARGET
mode : int = 0
inspiratory_pressure : float = 0.0
ie_ratio : float = 0.0
volume : float = 0.0
respiratory_rate : float = 0.0
peep : float = 0.0
fiO2_percent : float = 0.0
inhale_time : float = 0
inhale_trigger_enable : int = 0
exhale_trigger_enable : int = 0
volume_trigger_enable : int = 0
inhale_trigger_threshold : float = 0.0
exhale_trigger_threshold : float = 0.0
buffer_upper_pressure : float = 0.0
buffer_lower_pressure : float = 0.0
#pid_gain : float = 0.0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
tmp_mode = 0
(self.version,
self.timestamp,
tmp_payload_type,
tmp_mode ,
self.inspiratory_pressure,
self.ie_ratio ,
self.volume ,
self.respiratory_rate ,
self.peep ,
self.fiO2_percent ,
self.inhale_time ,
self.inhale_trigger_enable ,
self.exhale_trigger_enable ,
self.volume_trigger_enable ,
self.inhale_trigger_threshold ,
self.exhale_trigger_threshold ,
self.buffer_upper_pressure,
self.buffer_lower_pressure
#self.pid_gain
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self.mode = VENTILATION_MODE(tmp_mode)
self._byteArray = byteArray
# =======================================
# Personal data payload
# =======================================
@dataclass
class PersonalFormat(PayloadFormat):
_dataStruct = Struct("<BIB60s20sBcBB")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.PERSONAL
name : str = ""
patient_id : str = ""
age : int = 0
sex : str = ""
height : int = 0
weight : int = 0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
tmp_name = None
tmp_id = None
tmp_sex = None
(self.version,
self.timestamp,
tmp_payload_type,
tmp_name,
tmp_id,
self.age,
tmp_sex,
self.height,
self.weight) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self.name = tmp_name.decode().rstrip('\0')
self.patient_id = tmp_id.decode().rstrip('\0')
self.sex = tmp_sex.decode()
self._byteArray = byteArray
# =======================================
# Log msg payload
# =======================================
@dataclass
class LogMsgFormat(PayloadFormat):
_dataStruct = Struct("<BIB50s")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.LOGMSG
message : str = ""
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
tmp_chararray = ""
(self.version,
self.timestamp,
tmp_payload_type,
tmp_chararray) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.message = tmp_chararray.decode('ascii')
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# BATTERY data payload
# =======================================
@dataclass
class BatteryFormat(PayloadFormat):
_dataStruct = Struct("<BIBbbbbbbb")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.BATTERY
bat : int = 0
ok : int = 0
alarm : int = 0
rdy2buf : int = 0
bat85 : int = 0
prob_elec : int = 0
dummy : int = 0
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.bat ,
self.ok ,
self.alarm ,
self.rdy2buf ,
self.bat85 ,
self.prob_elec ,
self.dummy ,
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# cmd type payload
# =======================================
@dataclass
class CommandFormat(PayloadFormat):
_dataStruct = Struct("<BIBBBf")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.CMD
cmd_type: int = 0
cmd_code: int = 0
param: float = 0.0
def fromByteArray(self, byteArray):
cmd = 0
code = 0
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
cmd,
code,
self.param) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self.cmd_type = CMD_TYPE(cmd)
self.cmd_code = CMD_MAP[self.cmd_type.name].value(code)
self._byteArray = byteArray
# =======================================
# alarm type payload
# =======================================
@dataclass
class AlarmFormat(PayloadFormat):
_dataStruct = Struct("<BIBBBf")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.ALARM
alarm_type: int = 0
alarm_code: ALARM_CODES = ALARM_CODES.UNKNOWN
param: float = 0.0
def __eq__(self, other):
return (self.alarm_type == other.alarm_type) and (self.alarm_code == other.alarm_code)
def fromByteArray(self, byteArray):
alarm = 0
priority = 0
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
priority,
alarm,
self.param) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.alarm_type = ALARM_TYPE(priority)
self.alarm_code = ALARM_CODES(alarm)
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
#!/usr/bin/python3
# Simple UPS battery checker
......
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import json
class gpio:
......
../raspberry-dataserver/CommsCommon.py
\ No newline at end of file
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from struct import Struct
from enum import Enum, IntEnum, auto, unique
from dataclasses import dataclass, asdict, field, fields
from typing import Any, ClassVar, Dict
import logging
import binascii
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# VERSIONING
# change version in PayloadFormat for all data
# i.e. if and of DataFormat, CommandFormat or AlarmFormat change
# then change the RPI_VERSION
# =======================================
# Enum definitions
# =======================================
@unique
class CMD_TYPE(Enum):
GENERAL = 1
SET_DURATION = 2
SET_MODE = 3
SET_THRESHOLD_MIN = 4
SET_THRESHOLD_MAX = 5
SET_VALVE = 6
SET_PID = 7
SET_TARGET_PC_AC = 8
SET_TARGET_PC_AC_PRVC = 9
SET_TARGET_PC_PSV = 10
SET_TARGET_CPAP = 11
SET_TARGET_TEST = 12
SET_TARGET_CURRENT = 13
GET_TARGETS = 14
SET_PERSONAL = 15
GET_THRESHOLD_MIN = 16
GET_THRESHOLD_MAX = 17
@unique
class CMD_GENERAL(Enum):
START = 1
STOP = 2
RESET = 3
STANDBY = 4
GET_PERSONAL = 5
# Taken from the FSM doc. Correct as of 1400 on 20200417
@unique
class CMD_SET_DURATION(Enum):
PRE_CALIBRATION = 1
CALIBRATION = 2
BUFF_PURGE = 3
BUFF_FLUSH = 4
BUFF_PREFILL = 5
BUFF_FILL = 6
BUFF_PRE_INHALE = 7
INHALE = 8
PAUSE = 9
EXHALE = 10
@unique
class VENTILATION_MODE(Enum):
UNKNOWN = 0
PC_AC = 1
PC_AC_PRVC = 2
PC_PSV = 3
CPAP = 4
TEST = 5
PURGE = 6
FLUSH = 7
CURRENT = 100 # not settable
@unique
class CMD_SET_VALVE(Enum):
AIR_IN_ENABLE = 1
O2_IN_ENABLE = 2
PURGE_ENABLE = 3
INHALE_DUTY_CYCLE = 4
INHALE_OPEN_MIN = 5
INHALE_OPEN_MAX = 6
INHALE_TRIGGER_ENABLE = 7
EXHALE_TRIGGER_ENABLE = 8
@unique
class CMD_SET_PID(Enum):
KP = 1
KI = 2
KD = 3
PID_GAIN = 4
TARGET_FINAL_PRESSURE = 5
NSTEPS = 6
MAX_PATIENT_PRESSURE = 7
@unique
class CMD_SET_TARGET(Enum):
INSPIRATORY_PRESSURE = 1
RESPIRATORY_RATE = 2
IE_RATIO = 3
VOLUME = 4
PEEP = 5
FIO2_PERCENT = 6
INHALE_TIME = 7
INHALE_TRIGGER_THRESHOLD = 8
EXHALE_TRIGGER_THRESHOLD = 9
#PID_GAIN = 10
# for debugging only; not for UIs
INHALE_TRIGGER_ENABLE = 11
EXHALE_TRIGGER_ENABLE = 12
VOLUME_TRIGGER_ENABLE = 13
@unique
# class CMD_SET_PERSONAL(Enum):
# NAME = 1
# AGE = 2
# SEX = 3
# HEIGHT = 4
# WEIGHT = 5
@unique
class ALARM_TYPE(Enum):
PRIORITY_LOW = 1
PRIORITY_MEDIUM = 2
PRIORITY_HIGH = 3
@unique
class ALARM_CODES(Enum):
UNKNOWN = 0
APNEA = 1 # HP
CHECK_VALVE_EXHALE = 2 # HP
CHECK_P_PATIENT = 3 # HP
EXPIRATION_SENSE_FAULT_OR_LEAK = 4 # MP
EXPIRATION_VALVE_LEAK = 5 # MP
HIGH_FIO2 = 6 # MP
HIGH_PRESSURE = 7 # HP
HIGH_RR = 8 # MP
HIGH_VTE = 9 # MP
LOW_VTE = 10 # MP
HIGH_VTI = 11 # MP
LOW_VTI = 12 # MP
INTENTIONAL_STOP = 13 # HP
LOW_BATTERY = 14 # HP (LP) if AC power isn't (is) connected
LOW_FIO2 = 15 # HP
OCCLUSION = 16 # HP
HIGH_PEEP = 17 # HP
LOW_PEEP = 18 # HP
AC_POWER_DISCONNECTION = 19 # MP
BATTERY_FAULT_SRVC = 20 # MP
BATTERY_CHARGE = 21 # MP
AIR_FAIL = 22 # HP
O2_FAIL = 23 # HP
PRESSURE_SENSOR_FAULT = 24 # HP
ARDUINO_FAIL = 25 # HP
class CMD_MAP(Enum):
GENERAL = CMD_GENERAL
SET_DURATION = CMD_SET_DURATION
SET_MODE = VENTILATION_MODE
SET_VALVE = CMD_SET_VALVE
SET_PID = CMD_SET_PID
SET_TARGET_PC_AC = CMD_SET_TARGET
SET_TARGET_PC_AC_PRVC = CMD_SET_TARGET
SET_TARGET_PC_PSV = CMD_SET_TARGET
SET_TARGET_CPAP = CMD_SET_TARGET
SET_TARGET_TEST = CMD_SET_TARGET
SET_TARGET_CURRENT = CMD_SET_TARGET
SET_THRESHOLD_MIN = ALARM_CODES
SET_THRESHOLD_MAX = ALARM_CODES
GET_THRESHOLD_MIN = ALARM_CODES
GET_THRESHOLD_MAX = ALARM_CODES
GET_TARGETS = VENTILATION_MODE
# SET_PERSONAL = CMD_SET_PERSONAL
@unique
class BL_STATES(Enum):
UNKNOWN = 0
IDLE = 1
PRE_CALIBRATION = 2
CALIBRATION = 3
BUFF_PREFILL = 4
BUFF_FILL = 5
BUFF_PRE_INHALE = 6
INHALE = 7
PAUSE = 8
EXHALE = 9
STOP = 10
BUFF_PURGE = 11
BUFF_FLUSH = 12
STANDBY = 13
@unique
class PAYLOAD_TYPE(IntEnum):
UNSET = 0
DATA = 1
READBACK = 2
CYCLE = 3
THRESHOLDS = 4
CMD = 5
ALARM = 6
DEBUG = 7
IVT = 8
LOGMSG = 9
TARGET = 10
BATTERY = 11
LOOP_STATUS = 12
PERSONAL = 13
class HEVVersionError(Exception):
pass
@dataclass
class PayloadFormat():
# class variables excluded from init args and output dict
_RPI_VERSION: ClassVar[int] = field(default=0xB6, init=False, repr=False)
_dataStruct: ClassVar[Any] = field(default=Struct("<BIB"), init=False, repr=False)
_byteArray: ClassVar[bytearray] = field(default=None, init=False, repr=False)
# Meta information
version: int = 0
timestamp: int = 0
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.UNSET
@classmethod
def fromByteArray(cls, rec_bytes):
"""Automatically determine which subclass to initialise as"""
DATA_TYPE_TO_CLASS = {
1: DataFormat,
2: ReadbackFormat,
3: CycleFormat,
#4: ThresholdFormat,
5: CommandFormat,
6: AlarmFormat,
7: DebugFormat,
8: IVTFormat,
9: LogMsgFormat,
10: TargetFormat,
11: BatteryFormat,
12: LoopStatusFormat,
13: PersonalFormat
}
ReturnType = DATA_TYPE_TO_CLASS[rec_bytes[5]]
payload_obj = ReturnType()
payload_obj.fromByteArray(rec_bytes)
return payload_obj
@property
def byteArray(self) -> bytearray:
self.toByteArray()
return self._byteArray
@byteArray.setter
def byteArray(self, byte_array) -> None:
self._byteArray = byte_array
def toByteArray(self) -> None:
self.version = self._RPI_VERSION
self._byteArray = self._dataStruct.pack(*[
v.value if isinstance(v, IntEnum) or isinstance(v, Enum) else v
for v in asdict(self).values()
])
# check for mismatch between pi and microcontroller version
def checkVersion(self):
if self._RPI_VERSION != self.version :
raise HEVVersionError('Version Mismatch', "PI:", self._RPI_VERSION, "uC:", self.version)
def getSize(self) -> int:
return len(self.byteArray)
def getType(self) -> Any:
return self.payload_type if isinstance(self.payload_type, IntEnum) else PAYLOAD_TYPE(self.payload_type)
def getDict(self) -> Dict:
return {k: v.name if isinstance(v, IntEnum) or isinstance(v, Enum) else v for k, v in asdict(self).items()}
# =======================================
# fast data payload
# =======================================
@dataclass
class DataFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBBHfHffffHfHHffffffffff")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.DATA
# subclass member variables
fsm_state: BL_STATES = BL_STATES.IDLE
pressure_air_supply: int = 0
pressure_air_regulated: float = 0.0
pressure_o2_supply: int = 0
pressure_o2_regulated: float = 0.0
pressure_buffer: float = 0.0
pressure_inhale: float = 0.0
pressure_patient: float = 0.0
temperature_buffer: int = 0
pressure_diff_patient: float = 0.0
ambient_pressure: int = 0
ambient_temperature: int = 0
airway_pressure: float = 0.0
flow: float = 0.0
flow_calc : float = 0.0
volume : float = 0.0
target_pressure : float = 0.0 ##
process_pressure: float = 0.0
valve_duty_cycle: float = 0.0
proportional : float = 0.0
integral : float = 0.0 ##
derivative : float = 0.0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_state = 0
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
tmp_state,
self.pressure_air_supply,
self.pressure_air_regulated,
self.pressure_o2_supply,
self.pressure_o2_regulated,
self.pressure_buffer,
self.pressure_inhale,
self.pressure_patient,
self.temperature_buffer,
self.pressure_diff_patient,
self.ambient_pressure,
self.ambient_temperature,
self.airway_pressure,
self.flow,
self.flow_calc,
self.volume,
self.target_pressure ,
self.process_pressure,
self.valve_duty_cycle,
self.proportional ,
self.integral ,
self.derivative
) = self._dataStruct.unpack(byteArray)
self.fsm_state = BL_STATES(tmp_state)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# readback data payload
# =======================================
@dataclass
class ReadbackFormat(PayloadFormat):
_dataStruct = Struct("<BIBHHHHHHHHHHffBBBBBBBBBBBffffffB")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.READBACK
duration_pre_calibration: int = 0
duration_calibration: int = 0
duration_buff_purge: int = 0
duration_buff_flush: int = 0
duration_buff_prefill: int = 0
duration_buff_fill: int = 0
duration_buff_pre_inhale: int = 0
duration_inhale: int = 0
duration_pause: int = 0
duration_exhale: int = 0
valve_air_in: float = 0.0
valve_o2_in: float = 0.0
valve_inhale: int = 0
valve_exhale: int = 0
valve_purge: int = 0
ventilation_mode: int = VENTILATION_MODE.PC_AC
valve_inhale_percent: int = 0
valve_exhale_percent: int = 0
valve_air_in_enable: int = 0
valve_o2_in_enable: int = 0
valve_purge_enable: int = 0
inhale_trigger_enable: int = 0
exhale_trigger_enable: int = 0
peep: float = 0.0
inhale_exhale_ratio: float = 0.0
kp : float = 0.0
ki : float = 0.0
kd : float = 0.0
pid_gain : float = 0.0
max_patient_pressure : int = 0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_mode = 0
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.duration_pre_calibration,
self.duration_calibration,
self.duration_buff_purge,
self.duration_buff_flush,
self.duration_buff_prefill,
self.duration_buff_fill,
self.duration_buff_pre_inhale,
self.duration_inhale,
self.duration_pause,
self.duration_exhale,
self.valve_air_in,
self.valve_o2_in,
self.valve_inhale,
self.valve_exhale,
self.valve_purge,
tmp_mode,
self.valve_inhale_percent,
self.valve_exhale_percent,
self.valve_air_in_enable,
self.valve_o2_in_enable,
self.valve_purge_enable,
self.inhale_trigger_enable,
self.exhale_trigger_enable,
self.peep,
self.inhale_exhale_ratio,
self.kp ,
self.ki ,
self.kd ,
self.pid_gain ,
self.max_patient_pressure
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.ventilation_mode = VENTILATION_MODE(tmp_mode)
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# cycle data payload
# =======================================
@dataclass
class CycleFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBffffffffffffffHHB")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.CYCLE
respiratory_rate: float = 0.0
tidal_volume: float = 0.0
exhaled_tidal_volume: float = 0.0
inhaled_tidal_volume: float = 0.0
minute_volume: float = 0.0
exhaled_minute_volume: float = 0.0
inhaled_minute_volume: float = 0.0
lung_compliance: float = 0.0
static_compliance: float = 0.0
inhalation_pressure: float = 0.0
peak_inspiratory_pressure: float = 0.0
plateau_pressure: float = 0.0
mean_airway_pressure: float = 0.0
fiO2_percent: float = 0.0
apnea_index: int = 0
apnea_time: int = 0
mandatory_breath: int = 0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.respiratory_rate,
self.tidal_volume,
self.exhaled_tidal_volume,
self.inhaled_tidal_volume,
self.minute_volume,
self.exhaled_minute_volume,
self.inhaled_minute_volume,
self.lung_compliance,
self.static_compliance,
self.inhalation_pressure,
self.peak_inspiratory_pressure,
self.plateau_pressure,
self.mean_airway_pressure,
self.fiO2_percent,
self.apnea_index,
self.apnea_time,
self.mandatory_breath) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# debug data payload; this can change
# =======================================
@dataclass
class DebugFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBfffffffff")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.DEBUG
kp : float = 0.0
ki : float = 0.0
kd : float = 0.0
target_pressure : float = 0.0 ##
process_pressure: float = 0.0
valve_duty_cycle: float = 0.0
proportional : float = 0.0
integral : float = 0.0 ##
derivative : float = 0.0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.kp ,
self.ki ,
self.kd ,
self.target_pressure ,
self.process_pressure,
self.valve_duty_cycle,
self.proportional ,
self.integral ,
self.derivative
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# debug data payload; this can change
# =======================================
@dataclass
class LoopStatusFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBffIIBBB")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.LOOP_STATUS
duration_loop : float = 0.0
duration_loop_max : float = 0.0
dropped_send : int = 0
dropped_receive : int = 0
buffer_alarm : int = 0
buffer_cmd : int = 0
buffer_data : int = 0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.duration_loop ,
self.duration_loop_max,
self.dropped_send ,
self.dropped_receive ,
self.buffer_alarm ,
self.buffer_cmd ,
self.buffer_data ,
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# thresholds eata payload
# =======================================
# TODO
# =======================================
# IVT data payload
# =======================================
@dataclass
class IVTFormat(PayloadFormat):
_dataStruct = Struct("<BIBffffffffffBBBBBf")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.IVT
inhale_current : float = 0.0
exhale_current : float = 0.0
purge_current : float = 0.0
air_in_current : float = 0.0
o2_in_current : float = 0.0
inhale_voltage : float = 0.0
exhale_voltage : float = 0.0
purge_voltage : float = 0.0
air_in_voltage : float = 0.0
o2_in_voltage : float = 0.0
inhale_i2caddr : int = 0.0
exhale_i2caddr : int = 0.0
purge_i2caddr : int = 0.0
air_in_i2caddr : int = 0.0
o2_in_i2caddr : int = 0.0
system_temp : float = 0.0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.inhale_current ,
self.exhale_current ,
self.purge_current ,
self.air_in_current ,
self.o2_in_current ,
self.inhale_voltage ,
self.exhale_voltage ,
self.purge_voltage ,
self.air_in_voltage ,
self.o2_in_voltage ,
self.inhale_i2caddr ,
self.exhale_i2caddr ,
self.purge_i2caddr ,
self.air_in_i2caddr ,
self.o2_in_i2caddr ,
self.system_temp
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# Target data payload
# =======================================
@dataclass
class TargetFormat(PayloadFormat):
_dataStruct = Struct("<BIBBfffffffBBBffff")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.TARGET
mode : int = 0
inspiratory_pressure : float = 0.0
ie_ratio : float = 0.0
volume : float = 0.0
respiratory_rate : float = 0.0
peep : float = 0.0
fiO2_percent : float = 0.0
inhale_time : float = 0
inhale_trigger_enable : int = 0
exhale_trigger_enable : int = 0
volume_trigger_enable : int = 0
inhale_trigger_threshold : float = 0.0
exhale_trigger_threshold : float = 0.0
buffer_upper_pressure : float = 0.0
buffer_lower_pressure : float = 0.0
#pid_gain : float = 0.0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
tmp_mode = 0
(self.version,
self.timestamp,
tmp_payload_type,
tmp_mode ,
self.inspiratory_pressure,
self.ie_ratio ,
self.volume ,
self.respiratory_rate ,
self.peep ,
self.fiO2_percent ,
self.inhale_time ,
self.inhale_trigger_enable ,
self.exhale_trigger_enable ,
self.volume_trigger_enable ,
self.inhale_trigger_threshold ,
self.exhale_trigger_threshold ,
self.buffer_upper_pressure,
self.buffer_lower_pressure
#self.pid_gain
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self.mode = VENTILATION_MODE(tmp_mode)
self._byteArray = byteArray
# =======================================
# Personal data payload
# =======================================
@dataclass
class PersonalFormat(PayloadFormat):
_dataStruct = Struct("<BIB60s20sBcBB")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.PERSONAL
name : str = ""
patient_id : str = ""
age : int = 0
sex : str = ""
height : int = 0
weight : int = 0
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
tmp_name = None
tmp_id = None
tmp_sex = None
(self.version,
self.timestamp,
tmp_payload_type,
tmp_name,
tmp_id,
self.age,
tmp_sex,
self.height,
self.weight) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self.name = tmp_name.decode().rstrip('\0')
self.patient_id = tmp_id.decode().rstrip('\0')
self.sex = tmp_sex.decode()
self._byteArray = byteArray
# =======================================
# Log msg payload
# =======================================
@dataclass
class LogMsgFormat(PayloadFormat):
_dataStruct = Struct("<BIB50s")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.LOGMSG
message : str = ""
# for receiving DataFormat from microcontroller
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
#logging.info(f"bytearray size {len(byteArray)} ")
#logging.info(binascii.hexlify(byteArray))
tmp_payload_type = 0
tmp_chararray = ""
(self.version,
self.timestamp,
tmp_payload_type,
tmp_chararray) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.message = tmp_chararray.decode('ascii')
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# BATTERY data payload
# =======================================
@dataclass
class BatteryFormat(PayloadFormat):
_dataStruct = Struct("<BIBbbbbbbb")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.BATTERY
bat : int = 0
ok : int = 0
alarm : int = 0
rdy2buf : int = 0
bat85 : int = 0
prob_elec : int = 0
dummy : int = 0
# fill the struct from a byteArray,
def fromByteArray(self, byteArray):
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
self.bat ,
self.ok ,
self.alarm ,
self.rdy2buf ,
self.bat85 ,
self.prob_elec ,
self.dummy ,
) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
# =======================================
# cmd type payload
# =======================================
@dataclass
class CommandFormat(PayloadFormat):
_dataStruct = Struct("<BIBBBf")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.CMD
cmd_type: int = 0
cmd_code: int = 0
param: float = 0.0
def fromByteArray(self, byteArray):
cmd = 0
code = 0
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
cmd,
code,
self.param) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self.cmd_type = CMD_TYPE(cmd)
self.cmd_code = CMD_MAP[self.cmd_type.name].value(code)
self._byteArray = byteArray
# =======================================
# alarm type payload
# =======================================
@dataclass
class AlarmFormat(PayloadFormat):
_dataStruct = Struct("<BIBBBf")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.ALARM
alarm_type: int = 0
alarm_code: ALARM_CODES = ALARM_CODES.UNKNOWN
param: float = 0.0
def __eq__(self, other):
return (self.alarm_type == other.alarm_type) and (self.alarm_code == other.alarm_code)
def fromByteArray(self, byteArray):
alarm = 0
priority = 0
tmp_payload_type = 0
(self.version,
self.timestamp,
tmp_payload_type,
priority,
alarm,
self.param) = self._dataStruct.unpack(byteArray)
self.checkVersion()
self.alarm_type = ALARM_TYPE(priority)
self.alarm_code = ALARM_CODES(alarm)
self.payload_type = PAYLOAD_TYPE(tmp_payload_type)
self._byteArray = byteArray
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# Python monitoring code
# USAGE: python3 app.py
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# HEV monitoring application
# USAGE: python3 arduino_recorder.py
......
<!DOCTYPE html>
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
<html lang="en" class="{{'no-scroll-lock' if logs_active}}">
<head>
<meta charset="utf-8" />
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# HEV database dump for debugging
# USAGE: python3 database_dump.py -db database/HEV_monitoringDB.sqlite --start_date=20200408-1834
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import sys
import os
sys.path.insert(0, os.path.dirname(__file__))
from app import WEBAPP as application
\ No newline at end of file
from app import WEBAPP as application
../raspberry-dataserver/hevclient.py
\ No newline at end of file
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# client side for the data server to manage comms between UIs and LLI
#
# Author: Dónal Murray <donal.murray@cern.ch>
import asyncio
import time
import json
import threading
from typing import List, Dict, Union
from CommsCommon import PayloadFormat, PAYLOAD_TYPE
import logging
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# use /dev/shm (in memory tmpfs) to hold the data, should be stable over Flask shenanigans when restaring scripts
import mmap
import pickle
import os
mmFileName = "/dev/shm/HEVClient_lastData.mmap"
class HEVPacketError(Exception):
pass
class HEVClient(object):
def __init__(self, polling=True):
self._alarms = [] # db for alarms
self._personal = None # db for personal data
self._fastdata = None # db for sensor values
self._readback = None # db for sensor values
self._cycle = None # db for sensor values
self._target = None # db for sensor values
self._thresholds = None # db for sensor values
self._thresholds = [] # db for threshold settings
self._polling = polling # keep reading data into db
self._lock = threading.Lock() # lock for the database
self._mmFile = None
if( os.access( mmFileName, os.F_OK ) ):
self._mmFile = open(mmFileName, "a+b")
else:
self._mmFile = open(mmFileName, "x+b")
self._mmFile.write(b'0' * 10000) # ~10kb is enough I hope for one event
self._mmMap = mmap.mmap(self._mmFile.fileno(), 0) # Map to in memory object
self._mmMap.seek(0)
self._mmMap.write(pickle.dumps('Data not yet set')) # ensure no old or unset data in file
self._mmMap.flush()
# start polling in another thread unless told otherwise
if self._polling:
self.start_polling()
def __del__(self):
self._mmMap.close()
self._mmFile.close()
def start_polling(self):
"""start worker thread to update db in the background"""
worker = threading.Thread(target=self.start_client, daemon=True)
worker.start()
def start_client(self) -> None:
asyncio.run(self.polling())
async def polling(self) -> None:
"""open persistent connection with server"""
while True:
try:
reader, writer = await asyncio.open_connection("127.0.0.1", 54320)
# grab data from the socket as soon as it is available and dump it in the db
while self._polling:
try:
data = await reader.readuntil(separator=b'\0')
data = data[:-1] # snip off nullbyte
payload = json.loads(data.decode("utf-8"))
if payload["type"] == "keepalive":
#Still alive
continue
elif payload["type"] == "DATA":
with self._lock:
self._fastdata = payload["DATA"]
self._mmMap.seek(0)
self._mmMap.write(pickle.dumps(self._fastdata))
self._mmMap.flush()
elif payload["type"] == "READBACK":
with self._lock:
self._readback = payload["READBACK"]
elif payload["type"] == "CYCLE":
with self._lock:
self._cycle = payload["CYCLE"]
elif payload["type"] == "TARGET":
with self._lock:
self._target = payload["TARGET"]
elif payload["type"] == "PERSONAL":
with self._lock:
self._personal = payload["PERSONAL"]
elif payload["type"] == "THRESHOLDS":
with self._lock:
self._thresholds = payload["THRESHOLDS"]
elif payload["type"] == "ALARM":
with self._lock:
self._alarms = payload["ALARM"]
elif payload["type"] in [pt.name for pt in PAYLOAD_TYPE]:
# payload type is a valid payload type
pass
else:
raise HEVPacketError("Invalid broadcast type")
self._alarms = payload["alarms"]
#self._personal = payload["personal"]
self.get_updates(payload) # callback function to be overridden
except json.decoder.JSONDecodeError:
logging.warning(f"Could not decode packet: {data}")
except KeyError:
raise
# close connection
writer.close()
await writer.wait_closed()
except Exception as e:
# warn and reopen connection
logging.error(e)
await asyncio.sleep(2)
def get_updates(self, payload) -> None:
"""Overrideable function called after receiving data from the socket, with that data as an argument"""
pass
async def send_request(self, reqtype, cmdtype:str=None, cmd: str=None, param: str=None, alarm: str=None, personal: str=None) -> bool:
# open connection and send packet
reader, writer = await asyncio.open_connection("127.0.0.1", 54321)
payload = {"type": reqtype}
if reqtype == "CMD":
payload["cmdtype"] = cmdtype
payload["cmd"] = cmd
payload["param"] = param
elif reqtype == "ALARM":
payload["alarm_type"] = alarm["alarm_type"]
payload["alarm_code"] = alarm["alarm_code"]
payload["param"] = param
elif reqtype == "PERSONAL":
payload["name"] = personal["name"]
payload["age"] = int(personal["age"])
payload["sex"] = personal["sex"]
payload["height"] = int(personal["height"])
payload["weight"] = int(personal["weight"])
else:
raise HEVPacketError("Invalid packet type")
logging.info(payload)
packet = json.dumps(payload).encode() + b'\0'
writer.write(packet)
await writer.drain()
# wait for acknowledge
data = await reader.readuntil(separator=b'\0')
data = data[:-1]
try:
data = json.loads(data.decode("utf-8"))
except json.decoder.JSONDecodeError:
logging.warning(f"Could not decode packet: {data}")
# close connection to free up socket
writer.close()
await writer.wait_closed()
# check that acknowledge is meaningful
if data["type"] == "ack":
logging.info(f"Request type {reqtype} sent successfully")
return True
else:
logging.warning(f"Request type {reqtype} failed")
return False
def send_cmd(self, cmdtype:str, cmd: str, param: Union[float,int]=None) -> bool:
# send a cmd and wait to see if it's valid
#print(cmdtype, cmd, param)
return asyncio.run(self.send_request("CMD", cmdtype=cmdtype, cmd=cmd, param=param))
def ack_alarm(self, alarm: str) -> bool:
# acknowledge alarm to remove it from the hevserver list
return asyncio.run(self.send_request("ALARM", alarm=alarm))
#def send_personal(self, personal: Dict[str, str]=None ) -> bool:
def send_personal(self, personal: str) -> bool:
# acknowledge alarm to remove it from the hevserver list
return asyncio.run(self.send_request("PERSONAL", personal=personal))
def get_values(self) -> Dict:
# get sensor values from db
self._mmFile.seek(0)
try:
fastdata = pickle.load(self._mmFile)
except pickle.UnpicklingError as e:
logging.warning(f"Unpicking error {e}")
return None
if(type(fastdata) is dict):
return fastdata
else:
logging.warning("Missing fastdata")
return None
def get_readback(self) -> Dict:
# get readback from db
return self._readback
def get_cycle(self) -> Dict:
# get cycle data from db
return self._cycle
def get_personal(self) -> Dict:
# get personal data from db
return self._personal
def get_target(self) -> Dict:
# get target data from db
return self._target
def get_thresholds(self) -> Dict:
# get threshold data from db
return self._thresholds
def get_alarms(self) -> List[str]:
# get alarms from db
return self._alarms
if __name__ == "__main__":
# example implementation
# just import hevclient and do something like the following
hevclient = HEVClient()
time.sleep(2)
print(hevclient.send_cmd("GENERAL", "START"))
# Play with sensor values and alarms
for i in range(20):
values = hevclient.get_values() # returns a dict or None
alarms = hevclient.get_alarms() # returns a list of alarms currently ongoing
print(values)
if values is None:
i = i+1 if i > 0 else 0
else:
print(f"Values: {json.dumps(values, indent=4)}")
print(f"Alarms: {alarms}")
time.sleep(1)
# acknowledge the oldest alarm
try:
hevclient.ack_alarm(alarms[0]) # blindly assume we have one after 40s
except:
logging.info("No alarms received")
time.sleep(2)
print(f"Alarms: {hevclient.get_alarms()}")
# set a timeout
hevclient.send_cmd("SET_DURATION", "INHALE", 1111)
# check for the readback
for i in range(10):
print(f"Readback: {json.dumps(hevclient.get_readback(), indent=4)}")
print(f"Alarms: {hevclient.get_alarms()}")
time.sleep(1)
print(hevclient.send_cmd("GENERAL", "STOP"))
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// place to hard code chart parameters (can not make a separate .js as import of js not supported)
function chartParam(chartName) {
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
var chart_pressure;
var chart_flow;
var chart_volume;
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
// to quote the AAMI:
//For Pressure-Volume loops, the graph
//is required to use delivered volume on the vertical axis
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
var chart;
var refreshIntervalId;
var updateRefreshIntervalId;
......
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
var pause_charts = false;
var current_timestamp = -1;
......
<!DOCTYPE html>
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
<html lang="en" class="{{'no-scroll-lock' if logs_active}}">
<head>
<meta charset="utf-8" />
......
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
{% set charts_active = True %}
{% extends 'base.html' %}
......
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
{% set charts_active = True %}
{% extends 'base.html' %}
......
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
{% set chartsLoop_active = True %}
{% extends 'base.html' %}
{% block content %}
......
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
{% set fan_active = True %}
{% extends 'base.html' %}
......
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
{% set prototype_active = True %}
{% extends 'base.html' %}
......
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
{% set logs_active = True %}
{% extends 'base.html' %}
......
<!--
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
-->
{% set settings_active = True %}
{% extends 'base.html' %}
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import asyncio
import logging
......
../battery/BatteryLLI.py
\ No newline at end of file
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import asyncio
import logging
import copy
from CommsCommon import BatteryFormat
# Set up logging
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger().setLevel(logging.WARNING)
try:
import RPi.GPIO as gpio
except ModuleNotFoundError:
logging.warning("RPi gpio backend not found, will use dummy")
from hevgpio import gpio
gpio = gpio()
class BatteryLLI:
def __init__(self, timeout=1, dump=False):
super().__init__()
self._timeout = timeout
self._pins = {"bat" : 5,
"ok" : 6,
"alarm" : 12,
"rdy2buf" : 13,
"bat85" : 19,
"prob_elec": 7}
self._dump = dump
self._dumpfile = "share/battdump.dict"
self._dumpdata = None
if self._dump:
with open(self._dumpfile, 'w'):
pass
self._dummy = False
self.queue = asyncio.Queue()
try:
if gpio.DUMMY:
self._dummy = True
except:
pass
gpio.setmode(gpio.BCM)
for pin in self._pins:
gpio.setup(self._pins[pin], gpio.IN, pull_up_down=gpio.PUD_DOWN)
async def main(self) -> None:
while True:
await asyncio.sleep(self._timeout)
payload = BatteryFormat(dummy=self._dummy)
try:
for pin in self._pins:
setattr(payload, pin, gpio.input(self._pins[pin]))
self.queue.put_nowait(payload)
except asyncio.queues.QueueFull:
try:
self.queue.get_nowait()
self.queue.task_done()
self.queue.put_nowait(payload)
except Exception as e:
# Queue is being written from somewhere else. won't get here
logging.error(e)
continue
except Exception as e:
logging.error(f"Failed gpio data save: {e}")
continue
finally:
logging.debug(payload)
if self._dump == True:
with open(self._dumpfile, 'a') as f:
f.write(f"{payload.getDict()}\n")
if __name__ == "__main__":
try:
# schedule async tasks
loop = asyncio.get_event_loop()
# setup serial devices
battery = BatteryLLI()
asyncio.gather(battery.main(), return_exceptions=True)
loop.run_forever()
except asyncio.CancelledError:
pass
except KeyboardInterrupt:
logging.info("Closing LLI")
finally:
loop.close()
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import asyncio
import logging
logging.basicConfig(level=logging.WARNING, format='%(asctime)s - %(levelname)s - %(message)s')
......@@ -20,8 +43,8 @@ class ClientPlots(QtWidgets.QMainWindow):
def __init__(self, light=False, port=54322, *args, **kwargs):
super(ClientPlots, self).__init__(*args, **kwargs)
self.history_length = 300
self.xrange = 300
self.history_length = 1000
self.xrange = 1000
self.port = port
self.setWindowTitle("HEV socket debug")
......@@ -37,9 +60,14 @@ class ClientPlots(QtWidgets.QMainWindow):
self.graphWidget.nextRow()
self.timestamp = list(el*(-1) for el in range(self.history_length))[::-1]
self.PID_P = list(0 for _ in range(self.history_length))
self.PID_I = list(0 for _ in range(self.history_length))
self.PID_D = list(0 for _ in range(self.history_length))
# define plots here
self.names1 = ["flow", "flow_calc"]
self.names2 = ["volume"]
self.names3 = ["pressure_patient", "pressure_buffer"]
self.data1 = {name:list(0 for _ in range(self.history_length)) for name in self.names1}
self.data2 = {name:list(0 for _ in range(self.history_length)) for name in self.names2}
self.data3 = {name:list(0 for _ in range(self.history_length)) for name in self.names3}
if light:
# light theme
......@@ -48,6 +76,10 @@ class ClientPlots(QtWidgets.QMainWindow):
# dark theme
self.graphWidget.setBackground(mkColor(30,30,30))
# Add legend
self.flowPlot.addLegend()
self.volumePlot.addLegend()
self.pressurePlot.addLegend()
# Add grid
self.flowPlot.showGrid(x=True, y=True)
self.volumePlot.showGrid(x=True, y=True)
......@@ -60,9 +92,9 @@ class ClientPlots(QtWidgets.QMainWindow):
self.volumePlot.enableAutoRange('y', True)
self.pressurePlot.enableAutoRange('y', True)
# Plot styles
self.line1 = self.plot(self.flowPlot, self.timestamp, self.PID_D, "Flow", "00F")
self.line2 = self.plot(self.volumePlot, self.timestamp, self.PID_I, "Volume", "707")
self.line3 = self.plot(self.pressurePlot, self.timestamp, self.PID_P, "Airway Pressure", "077")
self.line1 = {self.names1[idx]:self.plot(self.flowPlot , self.timestamp, self.data1[self.names1[idx]], self.names1[idx], "00F", idx) for idx in range(len(self.names1))}
self.line2 = {self.names2[idx]:self.plot(self.volumePlot , self.timestamp, self.data2[self.names2[idx]], self.names2[idx], "707", idx) for idx in range(len(self.names2))}
self.line3 = {self.names3[idx]:self.plot(self.pressurePlot, self.timestamp, self.data3[self.names3[idx]], self.names3[idx], "077", idx) for idx in range(len(self.names3))}
# get data in another thread
self.worker = threading.Thread(target=self.polling, daemon=True)
......@@ -86,9 +118,10 @@ class ClientPlots(QtWidgets.QMainWindow):
finally:
loop.close()
def plot(self, canvas, x, y, plotname, color):
pen = pg.mkPen(color=color, width=3)
return canvas.plot(x, y, name=plotname, pen=pen)
def plot(self, canvas, x, y, plotname, color, idx = 0):
styles = [QtCore.Qt.SolidLine, QtCore.Qt.DashLine, QtCore.Qt.DotLine]
pen = pg.mkPen(color=color, width=3, style=styles[idx%3])
return canvas.plot(x, y, name=plotname, pen=pen)
async def redraw(self):
while True:
......@@ -109,16 +142,18 @@ class ClientPlots(QtWidgets.QMainWindow):
if brtype == "DATA":
self.statusBar().showMessage(f"Got data for timestamp {payload['timestamp']}")
logging.info("data acquired")
self.PID_D.append(payload["flow"])
self.PID_I.append(payload["volume"])
self.PID_P.append(payload["pressure_patient"])
if len(self.PID_D) > self.history_length:
self.PID_D = self.PID_D[1:]
self.PID_I = self.PID_I[1:]
self.PID_P = self.PID_P[1:]
self.line1.setData(self.timestamp, self.PID_D)
self.line2.setData(self.timestamp, self.PID_I)
self.line3.setData(self.timestamp, self.PID_P)
for name in self.names1:
self.data1[name].append(payload[name])
self.data1[name] = self.data1[name][1:]
self.line1[name].setData(self.timestamp, self.data1[name])
for name in self.names2:
self.data2[name].append(payload[name])
self.data2[name] = self.data2[name][1:]
self.line2[name].setData(self.timestamp, self.data2[name])
for name in self.names3:
self.data3[name].append(payload[name])
self.data3[name] = self.data3[name][1:]
self.line3[name].setData(self.timestamp, self.data3[name])
elif brtype == "READBACK":
pass
elif brtype == "CYCLE":
......@@ -131,11 +166,15 @@ class ClientPlots(QtWidgets.QMainWindow):
logging.info("personal data acquired")
pass
elif brtype == "ALARM":
logging.error(f"received ALARM {payload}")
logging.debug(f"received ALARM {payload}")
elif brtype == "IVT":
pass
elif brtype == "DEBUG":
pass
elif brtype == "BATTERY":
pass
elif brtype == "CMD":
pass
else:
raise KeyError
......
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from struct import Struct
from enum import Enum, IntEnum, auto, unique
from dataclasses import dataclass, asdict, field, fields
......@@ -279,7 +302,7 @@ class PayloadFormat():
@dataclass
class DataFormat(PayloadFormat):
# subclass dataformat
_dataStruct = Struct("<BIBBHfHffffHfHHfffffffff")
_dataStruct = Struct("<BIBBHfHffffHfHHffffffffff")
payload_type: PAYLOAD_TYPE = PAYLOAD_TYPE.DATA
# subclass member variables
fsm_state: BL_STATES = BL_STATES.IDLE
......@@ -296,7 +319,8 @@ class DataFormat(PayloadFormat):
ambient_temperature: int = 0
airway_pressure: float = 0.0
flow: float = 0.0
volume: float = 0.0
flow_calc : float = 0.0
volume : float = 0.0
target_pressure : float = 0.0 ##
process_pressure: float = 0.0
valve_duty_cycle: float = 0.0
......@@ -330,6 +354,7 @@ class DataFormat(PayloadFormat):
self.ambient_temperature,
self.airway_pressure,
self.flow,
self.flow_calc,
self.volume,
self.target_pressure ,
self.process_pressure,
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# Communication protocol between rasp and arduino based on HDLC format
# author Peter Svihra <peter.svihra@cern.ch>
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from CommsLLI import CommsLLI
from CommsCommon import *
import asyncio
......@@ -41,11 +64,12 @@ class Dependant(object):
# logging.info(f"Alarm: {payload.alarm_code} of priority: {payload.alarm_type}")
if payload.getType() == PAYLOAD_TYPE.DATA.value:
logging.info(f"payload received: {payload}")
#logging.info(f"payload received: {payload.timestamp} pc {payload.flow:3.6f} dc {payload.volume:3.6f} fsm {payload.fsm_state}")
#logging.info(f"payload received: {payload.pressure_buffer:3.6f} fsm {payload.fsm_state}")
#logging.info(f"Fsm state: {payload.fsm_state}")
fsm = payload.fsm_state
#logging.info(f"payload received: {payload}")
logging.info(f"payload received: {payload.timestamp} pc {payload.flow:3.6f} dc {payload.flow_calc:3.6f} fsm {payload.fsm_state}")
# #logging.info(f"payload received: {payload.timestamp} pc {payload.flow:3.6f} dc {payload.volume:3.6f} fsm {payload.fsm_state}")
# #logging.info(f"payload received: {payload.pressure_buffer:3.6f} fsm {payload.fsm_state}")
# #logging.info(f"Fsm state: {payload.fsm_state}")
# fsm = payload.fsm_state
#if payload.getType() == PAYLOAD_TYPE.IVT.value:
# logging.info(f"payload received: {payload} ")
#logging.info(f"IV: air {payload.air_in_current:.3f} o2 {payload.o2_in_current:.3f} purge {payload.purge_current:.3f} inhale {payload.inhale_current:.3f} exhale {payload.exhale_current:.3f} fsm {fsm} ")
......@@ -54,14 +78,16 @@ class Dependant(object):
# logging.info(f"payload received: inhale exhale ratio = {payload.inhale_exhale_ratio} ")
#if payload.getType() == PAYLOAD_TYPE.CYCLE.value:
# logging.info(f"payload received: {payload} ")
if payload.getType() == PAYLOAD_TYPE.READBACK.value:
#logging.info(f"payload received: {payload} ")
logging.info(f" READBACK PID {payload.kp:3.6f} {payload.ki:3.6f} {payload.kd:3.6f} ")
if payload.getType() == PAYLOAD_TYPE.DEBUG.value:
#if payload.getType() == PAYLOAD_TYPE.LOOP_STATUS.value:
# logging.info(f"payload received: {payload} ")
#if payload.getType() == PAYLOAD_TYPE.READBACK.value:
# #logging.info(f"payload received: {payload} ")
# logging.info(f" READBACK PID {payload.kp:3.6f} {payload.ki:3.6f} {payload.kd:3.6f} ")
#if payload.getType() == PAYLOAD_TYPE.DEBUG.value:
#logging.info(f" PID {payload.kp:3.6f} {payload.ki:3.6f} {payload.kd:3.6f} {payload.proportional:3.6f} {payload.integral:3.6f} {payload.derivative:3.6f} {payload.valve_duty_cycle:3.6f} {payload.target_pressure:3.6f} {payload.process_pressure:3.6f} fsm {fsm}")
logging.info(f" DEBUG PID {payload.kp:3.6f} {payload.ki:3.6f} {payload.kd:3.6f} ")
if payload.getType() == PAYLOAD_TYPE.LOGMSG.value:
logging.info(f"LOGMSG {payload.timestamp}:{payload.message} {fsm}")
# logging.info(f" DEBUG PID {payload.kp:3.6f} {payload.ki:3.6f} {payload.kd:3.6f} ")
#if payload.getType() == PAYLOAD_TYPE.LOGMSG.value:
# logging.info(f"LOGMSG {payload.timestamp}:{payload.message} {fsm}")
#if payload.getType() == PAYLOAD_TYPE.TARGET.value:
# logging.info(f"LOGMSG {payload} {fsm}")
#if hasattr(payload, 'ventilation_mode'):
......@@ -93,7 +119,7 @@ async def commsDebug():
send_cmd(cmd_type="SET_PID", cmd_code="KP", param=0.001)#
send_cmd(cmd_type="SET_PID", cmd_code="KI", param=0.0005)#5)# 0.0005
send_cmd(cmd_type="SET_PID", cmd_code="KD", param=0.001)#01)# 0.001
send_cmd(cmd_type="SET_TARGET_CURRENT", cmd_code="PID_GAIN", param=2)
#send_cmd(cmd_type="SET_TARGET_CURRENT", cmd_code="PID_GAIN", param=2)
#send_cmd(cmd_type="GET_TARGETS", cmd_code="TEST", param=0)
send_cmd(cmd_type="SET_PID", cmd_code="NSTEPS", param=3) #
......@@ -111,8 +137,8 @@ async def commsDebug():
send_cmd(cmd_type="SET_VALVE", cmd_code="INHALE_OPEN_MIN", param=0.53)
### NOTE : THESE ARE FOR TESTING ONLY, AS THEY OVERRIDE THE VALUES SET BY THE VENTILATION MODE
send_cmd(cmd_type="SET_TARGET_CURRENT", cmd_code="INHALE_TRIGGER_ENABLE", param=1)
send_cmd(cmd_type="SET_TARGET_CURRENT", cmd_code="EXHALE_TRIGGER_ENABLE", param=1)
send_cmd(cmd_type="SET_TARGET_CURRENT", cmd_code="INHALE_TRIGGER_ENABLE", param=0)
send_cmd(cmd_type="SET_TARGET_CURRENT", cmd_code="EXHALE_TRIGGER_ENABLE", param=0)
send_cmd(cmd_type="SET_TARGET_CURRENT", cmd_code="VOLUME_TRIGGER_ENABLE", param=0)
send_cmd(cmd_type="SET_VALVE", cmd_code="AIR_IN_ENABLE", param=1)
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from CommsLLI import CommsLLI
from CommsCommon import *
import asyncio
......@@ -42,23 +65,25 @@ class Dependant(object):
if payload.getType() == PAYLOAD_TYPE.DATA.value:
#logging.info(f"payload received: {payload}")
#logging.info(f"payload received: {payload.timestamp} p {payload.pressure_patient:3.2f} f {payload.flow:3.3f} base {payload.volume:3.3f} d {payload.flow - payload.volume:3.3f} {payload.fsm_state}")
#logging.info(f"payload received: {payload.pressure_o2_regulated}")
logging.info(f"payload received: {payload.timestamp} p {payload.pressure_patient:3.2f} dp {payload.pressure_diff_patient:3.3f} f {payload.flow:3.3f} base {payload.volume:3.3f} d {payload.flow - payload.volume:3.3f} {payload.fsm_state}")
#logging.info(f"Fsm state: {payload.fsm_state}")
fsm = payload.fsm_state
#fsm = payload.fsm_state
#if payload.getType() == PAYLOAD_TYPE.IVT.value:
# logging.info(f"payload received: {payload} ")
#logging.info(f"payload received: {payload} ")
#logging.info(f"IV: air {payload.air_in_current:.3f} o2 {payload.o2_in_current:.3f} purge {payload.purge_current:.3f} inhale {payload.inhale_current:.3f} exhale {payload.exhale_current:.3f} fsm {fsm} ")
#logging.info(f"payload received: {payload}")
#if hasattr(payload, 'inhale_exhale_ratio'):
# logging.info(f"payload received: inhale exhale ratio = {payload.inhale_exhale_ratio} ")
#if payload.getType() == PAYLOAD_TYPE.CYCLE.value:
# logging.info(f"payload received: {payload} ")
#logging.info(f"payload received: {payload} ")
#logging.info(f"payload received: {payload.fiO2_percent:3.9f} ")
#if payload.getType() == PAYLOAD_TYPE.READBACK.value:
# logging.info(f"payload received: {payload} {fsm}")
#if payload.getType() == PAYLOAD_TYPE.DEBUG.value:
# logging.info(f" PID {payload.kp:3.6f} {payload.ki:3.6f} {payload.kd:3.6f} {payload.proportional:3.6f} {payload.integral:3.6f} {payload.derivative:3.6f} {payload.valve_duty_cycle:3.6f} {payload.target_pressure:3.6f} {payload.process_pressure:3.6f} fsm {fsm}")
if payload.getType() == PAYLOAD_TYPE.PERSONAL.value:
logging.info(f"payload received: {payload} ")
#if payload.getType() == PAYLOAD_TYPE.PERSONAL.value:
# logging.info(f"payload received: {payload} ")
#if payload.getType() == PAYLOAD_TYPE.LOGMSG.value:
# logging.info(f"LOGMSG {payload.timestamp}:{payload.message} {fsm}")
#if payload.getType() == PAYLOAD_TYPE.TARGET.value:
......@@ -102,7 +127,7 @@ async def commsDebug():
#await asyncio.sleep(10)
#print('send personal info')
send_personal("Jessica Jones", 'abc1234', 29, 'F', 175, 58)
#send_personal("Jessica Jones", 'abc1234', 29, 'F', 175, 58)
#send_cmd(cmd_type="GET_THRESHOLD_MAX", cmd_code="APNEA")
#await asyncio.sleep(1)
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# Communication protocol based on HDLC format
# author Peter Svihra <peter.svihra@cern.ch>
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import asyncio
import serial_asyncio
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from CommsLLI import CommsLLI
from CommsCommon import *
import asyncio
......
#!/usr/bin/python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import sys
import re
import queue
......
#!/usr/bin/python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import sys
import re
import queue
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from CommsLLI import CommsLLI
from CommsCommon import *
import asyncio
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# client side for the data server to manage comms between UIs and LLI
#
# Author: Dónal Murray <donal.murray@cern.ch>
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# simple txt filereader frontend for HEVserver
# currently dedicated to very specific file format matching victor's sample.txt
......
../battery/hevgpio.py
\ No newline at end of file
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import json
class gpio:
DUMMY = True
IN = 0
OUT = 0
SPI = 0
I2C = 0
HARD_PWM = 0
SERIAL = 0
UNKNOWN = 0
PUD_DOWN = 0
BCM = 0
@staticmethod
def setmode(mode):
pass
@staticmethod
def setup(pin, mode, pull_up_down):
pass
def __init__(self):
self._dumpfile = "share/battdump.dict"
self._iter = self.generator()
self._fileline = self.update()
self._pins = {5: "bat",
6: "ok",
12: "alarm",
13: "rdy2buf",
19: "bat85",
7: "prob_elec"}
def update(self):
return json.loads(next(self._iter).replace("'",'"').replace("True","true").replace("False","false"))
def generator(self):
while True:
with open(self._dumpfile, 'r') as f:
try:
for line in f:
yield line
except StopIteration:
pass
def input(self, pin):
currline = self._fileline
if pin == 7:
# get next line from file
self._fileline = self.update()
return currline[self._pins[pin]]
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# data server to manage comms between UIs and LLI
#
# Author: Dónal Murray <donal.murray@cern.ch>
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# simple txt filereader frontend for HEVserver
# currently dedicated to very specific file format matching victor's sample.txt
......
#!/usr/bin/python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
import sys
import re
import queue
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from CommsLLI import CommsLLI
from CommsCommon import *
import asyncio
......
......@@ -177,30 +177,3 @@
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
{'version': 0, 'timestamp': 0, 'payload_type': 'BATTERY', 'bat': 0, 'ok': 1, 'alarm': 0, 'rdy2buf': 1, 'bat85': 1, 'prob_elec': 0, 'dummy': False}
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
from CommsLLI import CommsLLI
from CommsCommon import *
import asyncio
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# Front end generator for HEV raspberry pi data server
# author Dónal Murray <donal.murray@cern.ch>
......
#!/usr/bin/env python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# streamline arduino firmware upgrades for hev
#
# On first installation run:
......
#!/usr/bin/env bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
set -euo pipefail
for enum in CMD_TYPE CMD_GENERAL CMD_SET_TIMEOUT VENTILATION_MODE ALARM_TYPE ALARM_CODES; do
......
#!/bin/sh
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# called from the udev rule at /etc/udev/rules.d/88-hev.rules when arduino connected
echo "Arduino connected at $(date)" >> /tmp/hevcheck.log
#!/bin/bash
sed -i "1{
r licence_header_cpp.txt
h;d
};2{H;g;}" $1
#!/bin/bash
sed -i "2{
r licence_header_py.txt
h;d
};3{H;g;}" $1
// © Copyright CERN, Riga Technical University and University of Liverpool 2020.
// All rights not expressly granted are reserved.
//
// This file is part of hev-sw.
//
// hev-sw is free software: you can redistribute it and/or modify it under
// the terms of the GNU General Public Licence as published by the Free
// Software Foundation, either version 3 of the Licence, or (at your option)
// any later version.
//
// hev-sw 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 Licence
// for more details.
//
// You should have received a copy of the GNU General Public License along
// with hev-sw. If not, see <http://www.gnu.org/licenses/>.
//
// The authors would like to acknowledge the much appreciated support
// of all those involved with the High Energy Ventilator project
// (https://hev.web.cern.ch/).
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
#!/bin/bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
ssh -fCo "ExitOnForwardFailure yes" -L 54333:localhost:54321 pi@nuliv "nc -l localhost 54321 </dev/ttyACM0 >/dev/ttyACM0" && socat pty,link=$HOME/vmodem0,wait-slave tcp:localhost:54333 &
echo "Connect to \$HOME/vmodem0 for serial connection"
#!/usr/bin/python3
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
# Karol's dumb serial dumper
import serial
......
#!/usr/bin/env bash
# © Copyright CERN, Riga Technical University and University of Liverpool 2020.
# All rights not expressly granted are reserved.
#
# This file is part of hev-sw.
#
# hev-sw is free software: you can redistribute it and/or modify it under
# the terms of the GNU General Public Licence as published by the Free
# Software Foundation, either version 3 of the Licence, or (at your option)
# any later version.
#
# hev-sw 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 Licence
# for more details.
#
# You should have received a copy of the GNU General Public License along
# with hev-sw. If not, see <http://www.gnu.org/licenses/>.
#
# The authors would like to acknowledge the much appreciated support
# of all those involved with the High Energy Ventilator project
# (https://hev.web.cern.ch/).
set -euo pipefail
for struct in fast_data_format readback_data_format cycle_data_format cmd_format alarm_format; do
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment