Compare commits

84 Commits
main ... dev

Author SHA1 Message Date
d57baa3aff Updated telemetry to use new time_stamp feature 2026-04-06 00:43:11 +02:00
6260bc2352 Added injection counter module 2026-04-05 00:04:10 +02:00
4e04ae9a3f Speed average and display 2026-04-03 17:47:21 +02:00
49a17bdffd Partial frame rendering 2026-04-03 17:02:07 +02:00
a052888a38 Updated driver display to have lap count 2026-04-03 16:39:41 +02:00
ecccadc913 LapCounter finished and working 2026-04-03 16:20:45 +02:00
2ff1024a69 LapCounter initial impl 2026-04-03 14:43:03 +02:00
2234ed7109 GPS Line detect impl 2026-04-03 14:34:21 +02:00
f7d4162c4a Arming logic impl 2026-03-31 23:27:43 +02:00
a49147215e Updated GlobalTrackData struct to store precomputed circle radius 2026-03-31 22:42:49 +02:00
46c652181c Initial Vec2 impl ready for algo 2026-03-31 00:24:48 +02:00
5e19e7daa8 Added member variables to GPS for lap detection 2026-03-30 23:43:43 +02:00
22b7f82496 Debug logging 2026-03-30 23:30:50 +02:00
4960ce1aac Updated LICENSE 2026-03-30 22:56:36 +02:00
efd7119b32 Initial telemetry implementation 2026-03-30 22:44:14 +02:00
da6b23d78e Engine temp warning messages and bug fixes 2026-03-30 16:29:16 +02:00
3b2abd3f71 Refactor names to follow new convention 2026-03-29 15:04:28 +02:00
fedbdd2739 Added teng low and high update in config on task 2026-03-27 23:43:56 +01:00
812f391042 Wired in teng low and high in config and wired in command handler 2026-03-27 23:37:35 +01:00
618ed9a19f Added thermocouple module entry to module_id enum 2026-03-27 23:29:18 +01:00
d23a135b89 Added global engine temp in general data store 2026-03-27 23:27:28 +01:00
2c15ae43ae Initial thermocouple impl 2026-03-27 23:23:14 +01:00
3ea71788c2 Added battery low warning message 2026-03-27 18:28:00 +01:00
df0d3aef33 Updated config dump to include vbat cal value 2026-03-27 17:48:22 +01:00
d52cacad04 Fixed MOD_ALL router return bug 2026-03-27 17:21:51 +01:00
eab70f9bf9 Added battery module, cal factor refresh bug 2026-03-27 17:14:16 +01:00
f000924c05 Initial battery impl 2026-03-27 16:13:30 +01:00
6d47582eba Added basic primary driver display and display switch commands 2026-03-27 16:08:24 +01:00
a902600aa4 Unified commands to unit_action format 2026-03-27 15:27:36 +01:00
Hector van der Aa
2520c2b6ba Break out of commands to individual functions 2026-03-27 14:56:39 +01:00
1d7586129d Attempt to fix command paring error 2026-03-27 14:53:13 +01:00
Hector van der Aa
992b76cbd2 Added proper eeprom addressing and complete TRACK commands 2026-03-27 14:42:39 +01:00
3a396d6a42 Added timeout for GPS Init Complete message 2026-03-27 14:22:44 +01:00
5ae6149447 Fixed accidental loop in writing track to EEPROM 2026-03-27 14:20:10 +01:00
444aba79b2 Rename TRACK_LOAD to TRACK_PUT 2026-03-27 14:12:16 +01:00
Hector van der Aa
70c222284c Added track temp global function definitions 2026-03-27 14:07:51 +01:00
1d144fb638 Added track upload 2026-03-27 14:04:14 +01:00
Hector van der Aa
7f1494f18e Fixed lcd messages and gps triggering bugs 2026-03-27 13:01:49 +01:00
b1cb6b4234 Updated lcd to fix previous display bug 2026-03-27 12:51:00 +01:00
06495a089f Refactor to split .h into .h and .cpp pair 2026-03-27 12:38:31 +01:00
c6bcd3a9d7 Added track detect on fix and conditional loading 2026-03-25 20:02:33 +01:00
a5b53afb2c Added screen message on auto detect and added track global write on detect 2026-03-25 19:58:42 +01:00
21a5fd3244 Added track store and updated copy to and from volatile to single template function 2026-03-25 19:58:11 +01:00
555e85e00a Added auto track detection config task handler 2026-03-25 19:22:45 +01:00
99b17ac1bc Timing fixes in message system 2026-03-24 18:15:24 +01:00
ba61e9de68 Fix to call render_msg_gps_fix function in render switch 2026-03-24 18:08:07 +01:00
898879e427 Added first message task on gps lock !UNTESTED! 2026-03-24 17:53:00 +01:00
beffd09281 Added system_config->loop() to main loop 2026-03-24 09:14:39 +01:00
1fe4161f39 Initial impl for config with queue system 2026-03-24 09:14:27 +01:00
9e2407d06d Added NULL types for module target and task type 2026-03-24 09:14:05 +01:00
0fb09dd342 Updated config struct to new slot occupied logic 2026-03-24 09:13:50 +01:00
b83a2f7f03 Updated default frame duration 2026-03-24 09:13:36 +01:00
0cbee7066b Added copyright information and fixed typos 2026-03-24 00:23:17 +01:00
96cabf7b4e Implemented changes to main.cpp 2026-03-24 00:02:31 +01:00
58755f3140 Added global gps store 2026-03-24 00:02:17 +01:00
95743452d1 Added copy functions for gps_global_data 2026-03-24 00:02:01 +01:00
85049fab76 Updated modules to new inheritance model 2026-03-24 00:01:46 +01:00
25ad777247 Added module base for task routing 2026-03-24 00:01:36 +01:00
5b774f485a Updated platformio.ini 2026-03-23 22:15:30 +01:00
4449e1c224 Updated main.cpp 2026-03-23 22:15:20 +01:00
dc7c8477ca Initial command class impl 2026-03-23 22:15:07 +01:00
95e52c1274 Updated config to hold loaded track 2026-03-23 22:14:52 +01:00
96fea580c3 Updated track_data struct 2026-03-23 17:02:51 +01:00
63ad498ab7 Implemented changes to main.cpp 2026-03-23 16:51:08 +01:00
b6a14c6b14 Added render loop function and print overloads with cleared flag to avoid blocking 2026-03-23 16:51:01 +01:00
9c8280c829 Added gps_data struct 2026-03-23 16:50:13 +01:00
a969e514be Disabled DEEP_DEBUG mode 2026-03-23 16:50:00 +01:00
9df359e63e Update custom_types.h to simple struct 2026-03-22 23:51:01 +01:00
3299ca114d Impl DEEP_DEBUG for gps.h 2026-03-22 23:31:16 +01:00
c3ed38367b Refactor lcd.h DEEP_DEBUG to follow standard 2026-03-22 23:31:02 +01:00
4395e42e4c Corrected deep_debug function calls in lcd.h 2026-03-22 23:26:38 +01:00
44ff589cec Added DEEP_DEBUG to lcd.h 2026-03-22 23:25:00 +01:00
1c1f155ce0 Impl DEEP_DEBUG log level 2026-03-22 23:24:50 +01:00
faf4cae642 Simple config init impl 2026-03-22 23:16:43 +01:00
b8fc76af69 Updated custom_types.h with new magic header 2026-03-22 23:16:36 +01:00
91f4916b89 Basic config module 2026-03-22 23:16:15 +01:00
00a55d8411 Refactor GPS wrapper to semicolon constructor notation 2026-03-22 23:01:11 +01:00
ea32d8e5b4 Added format and ini files 2026-03-22 22:54:05 +01:00
def4197c0b Started main.cpp init 2026-03-22 22:53:51 +01:00
95b1f4f019 Added build flags 2026-03-22 22:53:42 +01:00
8954979aa1 Started custom_types.h 2026-03-22 22:53:20 +01:00
244cfa02c4 Basic unified system logger 2026-03-22 22:53:05 +01:00
e13f608b58 Basic LCD wrapper 2026-03-22 22:52:50 +01:00
364c711a04 Basic GPS wrapper 2026-03-22 22:52:34 +01:00
44 changed files with 3742 additions and 678 deletions

2
.clang-format Normal file
View File

@@ -0,0 +1,2 @@
BasedOnStyle: LLVM
BreakBeforeBraces: Attach

890
LICENSE
View File

@@ -1,674 +1,232 @@
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/>.
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 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.
Test
Copyright (C) 2026 h3cx
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:
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>
Test Copyright (C) 2026 h3cx
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.
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".
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/>.
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>.
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/philosophy/why-not-lgpl.html>.

View File

@@ -12,3 +12,11 @@
platform = atmelavr
board = megaatmega2560
framework = arduino
monitor_speed = 115200
monitor_echo = yes
monitor_eol = CRLF
monitor_filters = send_on_enter
lib_deps =
marcoschwartz/LiquidCrystal_I2C@^1.1.4
mikalhart/TinyGPSPlus@^1.1.0
adafruit/MAX6675 library@^1.1.2

10
src/base/module_base.h Normal file
View File

@@ -0,0 +1,10 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "base/task.h"
class ModuleBase {
public:
virtual int push(const Task& task) = 0;
};

6
src/base/modules.cpp Normal file
View File

@@ -0,0 +1,6 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "base/modules.h"
ModuleBase* module_registry[module::Count] = {nullptr};

9
src/base/modules.h Normal file
View File

@@ -0,0 +1,9 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "base/module_base.h"
#include "base/task.h"
extern ModuleBase* module_registry[module::Count];

38
src/base/ring_buffer.h Normal file
View File

@@ -0,0 +1,38 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <inttypes.h>
template<typename T, uint8_t SIZE>
class RingBuffer {
private:
T buffer_[SIZE];
volatile uint8_t head_ = 0;
volatile uint8_t tail_ = 0;
volatile uint8_t count_ = 0;
public:
int push(const T& item) {
if (count_ == SIZE) {
return 1;
}
buffer_[head_] = item;
head_ = (head_++) % SIZE;
count_++;
return 0;
}
int pop(T& item) {
if (count_ == 0) {
return 1;
}
item = buffer_[tail_];
tail_ = (tail_++) % SIZE;
count_--;
return 0;
}
bool isEmpty() const { return count_ == 0; }
bool isFull() const { return count_ == SIZE; }
uint8_t size() const { return count_; }
};

42
src/base/router.cpp Normal file
View File

@@ -0,0 +1,42 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "router.h"
namespace router {
int send(const Task &task) {
if (task.target_ == module::All) {
int ret = 0;
for (size_t index = 0; index < module::Count; index++) {
ModuleBase *module_ptr = module_registry[index];
if (module_ptr == nullptr) {
continue;
}
if (module_ptr->push(task) != 0) {
ret = 1;
}
}
return ret;
}
if (task.target_ >= module::Count) {
return 1;
}
ModuleBase *module_ptr = module_registry[task.target_];
if (module_ptr == nullptr) {
return 1;
}
return module_ptr->push(task);
}
int send(module::Id target, task::Type type, uint32_t data) {
Task task{target, type, data};
return send(task);
}
} // namespace router

13
src/base/router.h Normal file
View File

@@ -0,0 +1,13 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "base/task.h"
#include "base/module_base.h"
#include "base/modules.h"
namespace router {
int send(const Task& task);
int send(module::Id target, task::Type type, uint32_t data = 0);
}

67
src/base/task.h Normal file
View File

@@ -0,0 +1,67 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <inttypes.h>
#include <Arduino.h>
namespace module {
enum Id : uint8_t {
Cmd,
Config,
Gps,
Lcd,
Battery,
Thermocouple,
Telemetry,
LapCounter,
InjectionCounter,
Count,
Null,
All,
};
} // namespace module
namespace task {
enum Type : uint8_t {
Null,
DisplayGpsDebug,
DisplayDriverPrimary,
DisplayMsgGpsFix,
DisplayMsgTrackDetectOk,
DisplayMsgConfigNoTracks,
DisplayMsgBatteryLow,
DisplayMsgEngineTempLow,
DisplayMsgEngineTempHigh,
DisplayMsgLapCounterStart,
DisplayMsgLapCounterLapTime,
ConfigTrackDetect,
ConfigWriteTempTrack,
ConfigTrackDelete,
ConfigReset,
ConfigVbatCalSet,
ConfigVbatSetLow,
ConfigTengSetLow,
ConfigTengSetHigh,
BatteryCal,
AllConfigUpdated,
AllTrackLoaded,
AllStartLineTriggered,
AllGpsFixOk,
};
} // namespace task
struct Task {
Task(module::Id target = module::Null,
task::Type type = task::Null,
uint32_t data = 0)
: target_(target), type_(type), data_(data) {}
module::Id target_;
task::Type type_;
uint32_t data_;
};

71
src/custom_types.cpp Normal file
View File

@@ -0,0 +1,71 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "custom_types.h"
#include "math.h"
Vec2 eqRectProjection(const LatLng& target, const LatLng& ref) {
const float R = 6371000.0;
float lat0_r = ref.lat_ * M_PI / 180;
float lng0_r = ref.lng_ * M_PI / 180;
float lat1_r = target.lat_ * M_PI / 180;
float lng1_r = target.lng_ * M_PI / 180;
float lat0_cos = cos((lat0_r + lat1_r) * 0.5f);
Vec2 res;
res.x_ = (lng1_r - lng0_r) * lat0_cos * R;
res.y_ = (lat1_r - lat0_r) * R;
return res;
}
LatLng eqRectInverse(const Vec2& point, const LatLng& ref) {
const float R = 6371000.0f;
float lat0 = ref.lat_ * M_PI / 180.0f;
float lng0 = ref.lng_ * M_PI / 180.0f;
float cos_lat0 = cos(lat0);
// Recover latitude
float lat = lat0 + (point.y_ / R);
// Recover longitude
float lng = lng0 + (point.x_ / (R * cos_lat0));
LatLng res;
res.lat_ = lat * 180.0f / M_PI;
res.lng_ = lng * 180.0f / M_PI;
return res;
}
Vec2 vec2Midpoint(const Vec2& A, const Vec2& B) {
Vec2 res;
res.x_ = (A.x_ + B.x_) * 0.5f;
res.y_ = (A.y_ + B.y_) * 0.5f;
return res;
}
Vec2 vec2Sum(const Vec2& A, const Vec2& B) {
Vec2 res;
res.x_ = A.x_ + B.x_;
res.y_ = A.y_ + B.y_;
return res;
}
float vecMod(const Vec2& in) {
return sqrtf(in.x_*in.x_ + in.y_*in.y_);
}
float vec2SqDist(const Vec2& A, const Vec2& B) {
float deltaX = B.x_ - A.x_;
float deltaY = B.y_ - A.y_;
return deltaX * deltaX + deltaY * deltaY;
}
float vec2Cross(const Vec2& B, const Vec2& M) {
return B.x_ * M.y_ - B.y_ * M.x_;
}

91
src/custom_types.h Normal file
View File

@@ -0,0 +1,91 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <inttypes.h>
#include <string.h>
#define CONFIG_MAGIC 0xBEEF
struct VehicleConfig {
uint16_t magic_ = CONFIG_MAGIC;
bool auto_detect_track_ = true;
uint8_t track_fallback_ = 0;
bool track_slot_occupied_[8] = {false};
float vbat_calibration_ = 0;
float vbat_low_ = 0;
float teng_low_ = 0;
float teng_high_ = 0;
};
struct LatLng {
float lat_;
float lng_;
};
struct Vec2 {
float x_;
float y_;
};
Vec2 eqRectProjection(const LatLng& target, const LatLng& ref);
LatLng eqRectInverse(const Vec2& point, const LatLng& ref);
Vec2 vec2Midpoint(const Vec2& A, const Vec2& B);
Vec2 vec2Sum(const Vec2& A, const Vec2& B);
float vecMod(const Vec2& in);
float vec2SqDist(const Vec2& A, const Vec2& B);
float vec2Cross(const Vec2& B, const Vec2& M);
struct TrackData {
uint16_t magic_ = CONFIG_MAGIC;
unsigned short id_;
char name_[21];
LatLng point_a_;
LatLng point_b_;
};
struct GlobalTrackData {
bool loaded_ = false;
Vec2 center_;
float circle_radius_sq_;
TrackData root_;
};
struct GpsSubData {
uint32_t age_;
bool valid_;
float value_;
};
struct GpsData {
GpsSubData altitude_;
GpsSubData lat_;
GpsSubData lng_;
GpsSubData speed_;
GpsSubData course_;
uint32_t time_;
uint32_t time_write_time_;
uint32_t num_fix_;
};
template<typename T>
inline void copyFromVolatile(T& dst, const volatile T& src) {
memcpy(&dst, (const void*)&src, sizeof(T));
}
template<typename T>
inline void copyToVolatile(volatile T& dst, const T& src) {
memcpy((void*)&dst, &src, sizeof(T));
}
static inline uint32_t hhmmsscc_to_cs(uint32_t t) {
uint32_t hours = t / 1000000;
uint32_t minutes = (t / 10000) % 100;
uint32_t seconds = (t / 100) % 100;
uint32_t cs = t % 100;
return hours * 360000 +
minutes * 6000 +
seconds * 100 +
cs;
}

14
src/data/config_store.cpp Normal file
View File

@@ -0,0 +1,14 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "data/config_store.h"
volatile VehicleConfig config_global = {};
void configGlobalRead(VehicleConfig& out) {
copyFromVolatile(out, config_global);
}
void configGlobalWrite(const VehicleConfig& in) {
copyToVolatile(config_global, in);
}

12
src/data/config_store.h Normal file
View File

@@ -0,0 +1,12 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "custom_types.h"
#include <EEPROM.h>
extern volatile VehicleConfig config_global;
void configGlobalRead(VehicleConfig& out);
void configGlobalWrite(const VehicleConfig& in);

25
src/data/eeprom_layout.h Normal file
View File

@@ -0,0 +1,25 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <inttypes.h>
namespace eeprom_layout {
static const uint16_t TOTAL_BYTES = 4096;
static const uint16_t CONFIG_ADDR = 0;
static const uint16_t CONFIG_RESERVED_BYTES = 256;
static const uint16_t TRACK_SLOTS = 8;
static const uint16_t TRACK_SLOT_BYTES = 128;
static const uint16_t TRACK_BASE_ADDR = CONFIG_ADDR + CONFIG_RESERVED_BYTES;
static const uint16_t TRACK_END_ADDR = TRACK_BASE_ADDR + (TRACK_SLOTS * TRACK_SLOT_BYTES);
static const uint16_t FREE_AFTER_TRACKS = TOTAL_BYTES - TRACK_END_ADDR;
static_assert(TRACK_END_ADDR <= TOTAL_BYTES, "EEPROM layout exceeds physical storage");
inline uint16_t trackSlotAddr(uint8_t idx) {
return TRACK_BASE_ADDR + ((idx - 1) * TRACK_SLOT_BYTES);
}
} // namespace eeprom_layout

View File

@@ -0,0 +1,40 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "general_store.h"
volatile float vbat_global = 0;
volatile float teng_global = 0;
volatile int gps_trigger_global = 0;
volatile uint32_t last_lap_time_global = 0;
volatile uint16_t lap_count_global = 0;
volatile float speed_avg_global = 0;
volatile uint16_t injection_ctr_global = 0;
void vbatGlobalRead(float &out) { out = vbat_global; }
void vbatGlobalWrite(const float &in) { vbat_global = in; }
void tengGlobalRead(float &out) { out = teng_global; }
void tengGlobalWrite(const float &in) { teng_global = in; }
void gpsTriggerGlobalRead(int &out) { out = gps_trigger_global; }
void gpsTriggerGlobalWrite(const int &in) { gps_trigger_global = in; }
void lastLapTimeGlobalRead(uint32_t &out) { out = last_lap_time_global; }
void lastLapTimeGlobalWrite(const uint32_t &in) { last_lap_time_global = in; }
void lapCountGlobalRead(uint16_t &out) { out = lap_count_global; }
void lapCountGlobalWrite(const uint16_t &in) { lap_count_global = in; }
void speedAvgGlobalRead(float &out) { out = speed_avg_global; }
void speedAvgGlobalWrite(const float &in) { speed_avg_global = in; }
void injectionCtrGlobalRead(uint16_t &out) { out = injection_ctr_global; }
void injectionCtrGlobalWrite(const uint16_t &in) { injection_ctr_global = in; }

34
src/data/general_store.h Normal file
View File

@@ -0,0 +1,34 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <inttypes.h>
extern volatile float vbat_global;
extern volatile float teng_global;
extern volatile int gps_trigger_global;
extern volatile uint32_t last_lap_time_global;
extern volatile uint16_t lap_count_global;
extern volatile float speed_avg_global;
extern volatile uint16_t injection_ctr_global;
void vbatGlobalRead(float& out);
void vbatGlobalWrite(const float& in);
void tengGlobalRead(float& out);
void tengGlobalWrite(const float& in);
void gpsTriggerGlobalRead(int& out);
void gpsTriggerGlobalWrite(const int& in);
void lastLapTimeGlobalRead(uint32_t& out);
void lastLapTimeGlobalWrite(const uint32_t& in);
void lapCountGlobalRead(uint16_t& out);
void lapCountGlobalWrite(const uint16_t& in);
void speedAvgGlobalRead(float& out);
void speedAvgGlobalWrite(const float& in);
void injectionCtrGlobalRead(uint16_t& out);
void injectionCtrGlobalWrite(const uint16_t& in);

14
src/data/gps_store.cpp Normal file
View File

@@ -0,0 +1,14 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "gps_store.h"
volatile GpsData gps_data_global = {};
void gpsGlobalRead(GpsData& out) {
copyFromVolatile(out, gps_data_global);
}
void gpsGlobalWrite(const GpsData& in) {
copyToVolatile(gps_data_global, in);
}

11
src/data/gps_store.h Normal file
View File

@@ -0,0 +1,11 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "custom_types.h"
extern volatile GpsData gps_data_global;
void gpsGlobalRead(GpsData& out);
void gpsGlobalWrite(const GpsData& in);

39
src/data/track_store.cpp Normal file
View File

@@ -0,0 +1,39 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "data/track_store.h"
#include "data/eeprom_layout.h"
volatile GlobalTrackData track_data_global = {};
volatile TrackData track_data_temp_global = {};
void trackGlobalRead(GlobalTrackData& out) {
copyFromVolatile(out, track_data_global);
}
int trackGlobalRead(unsigned short idx, GlobalTrackData& out) {
if (idx < 1 || idx > 8) {
return 1;
}
TrackData track_data;
EEPROM.get(eeprom_layout::trackSlotAddr(idx), track_data);
if (track_data.magic_ != CONFIG_MAGIC) {
return 1;
}
out.loaded_ = true;
out.root_ = track_data;
return 0;
}
void trackGlobalWrite(const GlobalTrackData& in) {
copyToVolatile(track_data_global, in);
}
void trackTempGlobalRead(TrackData& out) {
copyFromVolatile(out, track_data_temp_global);
}
void trackTempGlobalWrite(const TrackData& in) {
copyToVolatile(track_data_temp_global, in);
}

17
src/data/track_store.h Normal file
View File

@@ -0,0 +1,17 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "custom_types.h"
#include <EEPROM.h>
extern volatile GlobalTrackData track_data_global;
extern volatile TrackData track_data_temp_global;
void trackGlobalRead(GlobalTrackData& out);
int trackGlobalRead(unsigned short idx, GlobalTrackData& out);
void trackGlobalWrite(const GlobalTrackData& in);
void trackTempGlobalRead(TrackData& out);
void trackTempGlobalWrite(const TrackData& in);

8
src/flags.h Normal file
View File

@@ -0,0 +1,8 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#define INFO
#define WARN
#define ERROR
#define DEBUG
// #define DEEP_DEBUG

View File

@@ -1,18 +1,103 @@
#include <Arduino.h>
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "flags.h"
#include "modules/cmd/cmd.h"
#include "modules/config/config.h"
#include "modules/gps/gps.h"
#include "modules/lcd/lcd.h"
#include "modules/logger/system_logger.h"
#include <Arduino.h>
#include <avr/wdt.h>
#include "base/modules.h"
#include "base/module_base.h"
#include "base/router.h"
#include "modules/battery/battery.h"
#include "modules/thermocouple/thermocouple.h"
#include "modules/telemetry/telemetry.h"
#include "modules/lap_counter/lap_counter.h"
#include "modules/injection_counter/injection_counter.h"
SystemLogger *logger = new SystemLogger(&Serial);
Lcd *display = new Lcd(logger);
Gps *gps_module = new Gps(&Serial2, logger);
Config *system_config = new Config(logger);
Cmd *command_handler = new Cmd(&Serial, logger);
Battery *battery_module = new Battery(logger);
Thermocouple *thermocouple_module = new Thermocouple(logger);
Telemetry *telemetry_module = new Telemetry(&Serial1, logger);
LapCounter *lap_counter_modules = new LapCounter(logger);
InjectionCounter *inj_counter_module = new InjectionCounter(logger);
// put function declarations here:
int myFunction(int, int);
void setup() {
// put your setup code here, to run once:
int result = myFunction(2, 3);
wdt_disable();
module_registry[module::Lcd] = display;
module_registry[module::Gps] = gps_module;
module_registry[module::Config] = system_config;
module_registry[module::Cmd] = command_handler;
module_registry[module::Battery] = battery_module;
module_registry[module::Thermocouple] = thermocouple_module;
module_registry[module::Telemetry] = telemetry_module;
module_registry[module::LapCounter] = lap_counter_modules;
module_registry[module::InjectionCounter] = inj_counter_module;
display->init();
display->printMessage("Starting Initialization");
delay(750);
display->printMessage("Cmd Init...");
command_handler->init();
delay(750);
display->printMessage("Cmd Init Complete");
delay(750);
display->printMessage("Config Init...");
int result = system_config->autoInit();
delay(750);
if (result != 0) {
display->printMessage("Configuration Read Failed");
} else {
display->printMessage("Config Init Complete");
}
delay(750);
display->printMessage("GPS Init...");
gps_module->init();
lap_counter_modules->init();
delay(750);
display->printMessage("GPS Init Complete");
delay(750);
display->printMessage("Sensors Init...");
battery_module->init();
thermocouple_module->init();
inj_counter_module->init();
delay(750);
display->printMessage("Sensors Init Complete");
delay(750);
display->printMessage("Telemetry Init...");
telemetry_module->init();
delay(750);
display->printMessage("Telemetry Init Complete");
delay(750);
router::send(module::Lcd, task::DisplayDriverPrimary);
}
void loop() {
// put your main code here, to run repeatedly:
}
// put function definitions here:
int myFunction(int x, int y) {
return x + y;
gps_module->loop();
lap_counter_modules->loop();
display->loop();
command_handler->parseTask();
system_config->loop();
battery_module->loop();
thermocouple_module->loop();
telemetry_module->loop();
inj_counter_module->loop();
}

View File

@@ -0,0 +1,85 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "battery.h"
#include "base/router.h"
#include "data/config_store.h"
#include "data/general_store.h"
int Battery::calibrate(const Task &task) {
float actual_voltage;
memcpy(&actual_voltage, &task.data_, sizeof(float));
int adc_read = analogRead(VBAT_PIN);
float cal_factor = actual_voltage / adc_read;
uint32_t output_val;
memcpy(&output_val, &cal_factor, sizeof(uint32_t));
router::send(module::Config, task::ConfigVbatCalSet, output_val);
return 0;
}
int Battery::push(const Task &task) { return queue_.push(task); }
Battery::Battery() : logger_(nullptr) {}
Battery::Battery(SystemLogger *logger) : logger_(logger) {}
Battery::~Battery() {}
int Battery::init() {
pinMode(VBAT_PIN, INPUT);
VehicleConfig config;
configGlobalRead(config);
calibration_ = config.vbat_calibration_;
low_threshold_ = config.vbat_low_;
return 0;
}
int Battery::loop(unsigned long timeout_ms) {
(void)timeout_ms;
if (millis() > last_read_at_ + update_interval_) {
int adc_read = analogRead(VBAT_PIN);
vbat_ = calibration_ * adc_read;
vbatGlobalWrite(vbat_);
if (vbat_ < low_threshold_) {
if (warning_sent_at_ == 0 ||
millis() > warning_sent_at_ + warning_timeout_) {
router::send(module::Lcd, task::DisplayMsgBatteryLow, 2000);
warning_sent_at_ = millis();
}
}
last_read_at_ = millis();
}
Task active_task;
int res = queue_.pop(active_task);
if (res == 0) {
if (active_task.target_ == module::Battery) {
switch (active_task.type_) {
case task::BatteryCal:
this->calibrate(active_task);
break;
default:
break;
}
} else if (active_task.target_ == module::All) {
switch (active_task.type_) {
case task::AllConfigUpdated: {
VehicleConfig config;
configGlobalRead(config);
calibration_ = config.vbat_calibration_;
low_threshold_ = config.vbat_low_;
break;
}
default:
break;
}
}
}
return 0;
}

View File

@@ -0,0 +1,33 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#define VBAT_PIN A3
#include "base/module_base.h"
#include "base/ring_buffer.h"
#include "custom_types.h"
#include "modules/logger/system_logger.h"
#include <Arduino.h>
class Battery : public ModuleBase {
private:
SystemLogger *logger_;
RingBuffer<Task, 16> queue_;
float vbat_ = 0;
float calibration_ = 0;
float low_threshold_ = 0;
unsigned long warning_sent_at_ = 0;
unsigned long warning_timeout_ = 10000;
unsigned long update_interval_ = 1000;
unsigned long last_read_at_ = 0;
int calibrate(const Task& task);
public:
int push(const Task &task) override;
Battery();
Battery(SystemLogger *logger);
~Battery();
int init();
int loop(unsigned long timeout_ms = 500);
};

640
src/modules/cmd/cmd.cpp Normal file
View File

@@ -0,0 +1,640 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "cmd.h"
#include <string.h>
#include "data/track_store.h"
#include "data/config_store.h"
#include "data/general_store.h"
#include "base/router.h"
char *Cmd::trimArg(char *input) {
if (input == nullptr) {
return nullptr;
}
while (*input == ' ' || *input == '\t' || *input == '\r' || *input == '\n') {
input++;
}
if (*input == '\0') {
return input;
}
char *end = input + strlen(input) - 1;
while (end >= input &&
(*end == ' ' || *end == '\t' || *end == '\r' || *end == '\n')) {
*end = '\0';
end--;
}
return input;
}
unsigned short Cmd::splitArgs(char *input, char *argv[], unsigned short max_args) {
unsigned short argc = 0;
char *p = input;
char *token_start = input;
if (input == nullptr || argv == nullptr || max_args == 0) {
return 0;
}
if (*input == '\0') {
return 0;
}
while (argc < max_args) {
if (*p == ',' || *p == '\0') {
char separator = *p;
*p = '\0';
argv[argc] = trimArg(token_start);
argc++;
if (separator == '\0') {
break;
}
token_start = p + 1;
}
p++;
}
return argc;
}
Cmd::CommandId Cmd::parseCommandName(const char *input) {
if (input == nullptr) {
return Unknown;
}
if (strcmp(input, "REBOOT") == 0) {
return Reboot;
}
if (strcmp(input, "CFG_DUMP") == 0) {
return ConfigDump;
}
if (strcmp(input, "TRACK_PUT") == 0) {
return PutTrack;
}
if (strcmp(input, "TRACK_DELETE") == 0) {
return DeleteTrack;
}
if (strcmp(input, "TRACK_DUMP") == 0) {
return DumpTrack;
}
if (strcmp(input, "CFG_RESET") == 0) {
return ConfigReset;
}
if (strcmp(input, "TRACK_AUTODETECT") == 0) {
return TrackAutodetect;
}
if (strcmp(input, "DISPLAY_GPS_DEBUG") == 0) {
return DisplayGpsDebug;
}
if (strcmp(input, "DISPLAY_GPS_LINE_DEBUG") == 0) {
return DisplayGpsLineDebug;
}
if (strcmp(input, "DISPLAY_DRIVER_PRIMARY") == 0) {
return DisplayDriverPrimary;
}
if (strcmp(input, "BATTERY_CAL") == 0) {
return BatteryCal;
}
if (strcmp(input, "BATTERY_PRINT_VBAT") == 0) {
return BatteryPrintVbat;
}
if (strcmp(input, "BATTERY_SET_LOW") == 0) {
return BatterySetLow;
}
if (strcmp(input, "THERMO_SET_LOW") == 0) {
return ThermoSetLow;
}
if (strcmp(input, "THERMO_SET_HIGH") == 0) {
return ThermoSetHigh;
}
return Unknown;
}
int Cmd::parseTrackSlotId(const char *id_str, unsigned short &id_out) {
if (id_str == nullptr || id_str[0] == '\0') {
return 1;
}
id_out = strtoul(id_str, nullptr, 10);
if (id_out < 1 || id_out > 8) {
return 1;
}
return 0;
}
int Cmd::dumpTrackSlot(unsigned short id) {
VehicleConfig config;
configGlobalRead(config);
bool occupied = config.track_slot_occupied_[id - 1];
GlobalTrackData track_data;
int result = trackGlobalRead(id, track_data);
if (result != 0) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("Track slot " + String(id) + " has no valid track data");
}
#endif
return 1;
}
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Track dump for slot " + String(id));
logger_->info(String("\tOccupied flag: ") + String(occupied));
logger_->info(String("\tID: ") + String(track_data.root_.id_));
logger_->info(String("\tName: ") + String(track_data.root_.name_));
logger_->info(String("\tPoint A lat: ") + String(track_data.root_.point_a_.lat_, 6));
logger_->info(String("\tPoint A lng: ") + String(track_data.root_.point_a_.lng_, 6));
logger_->info(String("\tPoint B lat: ") + String(track_data.root_.point_b_.lat_, 6));
logger_->info(String("\tPoint B lng: ") + String(track_data.root_.point_b_.lng_, 6));
}
#endif
return 0;
}
int Cmd::handleRebootCommand(unsigned short argc) {
if (argc != 1) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("REBOOT expects no arguments");
}
#endif
return 1;
}
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Rebooting");
}
#endif
delay(200);
wdt_enable(WDTO_15MS);
while (true) {
}
return 0;
}
int Cmd::handleDumpConfigCommand(unsigned short argc) {
if (argc != 1) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("DUMPCFG expects no arguments");
}
#endif
return 1;
}
#ifdef INFO
if (logger_ != nullptr) {
logger_->dumpConfig();
}
#endif
return 0;
}
int Cmd::handleTrackPutCommand(unsigned short argc, char *argv[]) {
if (argc != 7) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("TRACK_PUT expects 6 arguments");
}
#endif
return 1;
}
TrackData new_track;
if (parseTrackSlotId(argv[1], new_track.id_) != 0) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error(String("ID out of range: ") + String(argv[1]));
}
#endif
return 1;
}
strncpy(new_track.name_, argv[2], sizeof(new_track.name_) - 1);
new_track.name_[sizeof(new_track.name_) - 1] = '\0';
LatLng point_a;
point_a.lat_ = strtod(argv[3], nullptr);
point_a.lng_ = strtod(argv[4], nullptr);
new_track.point_a_ = point_a;
LatLng point_b;
point_b.lat_ = strtod(argv[5], nullptr);
point_b.lng_ = strtod(argv[6], nullptr);
new_track.point_b_ = point_b;
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Loading new track");
logger_->info(String("ID: ") + String(new_track.id_));
logger_->info(String("Name: ") + new_track.name_);
logger_->info(String("Point A lat: ") + String(new_track.point_a_.lat_));
logger_->info(String("Point A lng: ") + String(new_track.point_a_.lng_));
logger_->info(String("Point B lat: ") + String(new_track.point_b_.lat_));
logger_->info(String("Point B lng: ") + String(new_track.point_b_.lng_));
}
#endif
trackTempGlobalWrite(new_track);
return router::send(module::Config, task::ConfigWriteTempTrack);
}
int Cmd::handleTrackDeleteCommand(unsigned short argc, char *argv[]) {
if (argc != 2) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("TRACK_DELETE expects 1 argument");
}
#endif
return 1;
}
unsigned short id;
if (parseTrackSlotId(argv[1], id) != 0) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error(String("ID out of range: ") + String(argv[1]));
}
#endif
return 1;
}
return router::send(module::Config, task::ConfigTrackDelete, id);
}
int Cmd::handleTrackDumpCommand(unsigned short argc, char *argv[]) {
if (argc != 2) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("TRACK_DUMP expects 1 argument");
}
#endif
return 1;
}
unsigned short id;
if (parseTrackSlotId(argv[1], id) != 0) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error(String("ID out of range: ") + String(argv[1]));
}
#endif
return 1;
}
return this->dumpTrackSlot(id);
}
int Cmd::handleConfigResetCommand(unsigned short argc) {
if (argc != 1) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("CFG_RESET expects no arguments");
}
#endif
return 1;
}
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Resetting config");
}
#endif
return router::send(module::Config, task::ConfigReset);
}
int Cmd::handleTrackAutodetectCommand(unsigned short argc) {
if (argc != 1) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("TRACK_AUTODETECT expects no arguments");
}
#endif
return 1;
}
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Detecting track");
}
#endif
return router::send(module::Config, task::ConfigTrackDetect, 1);
}
int Cmd::handleDisplayGpsDebug(unsigned short argc) {
if (argc != 1) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("DISPLAY_GPS_DEBUG expects no arguments");
}
#endif
return 1;
}
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Switching to GPS_DEBUG display");
}
#endif
return router::send(module::Lcd, task::DisplayGpsDebug);
}
int Cmd::handleDisplayDriverPrimary(unsigned short argc) {
if (argc != 1) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("DISPLAY_DRIVER_PRIMARY expects no arguments");
}
#endif
return 1;
}
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Switching to DRIVER_PRIMARY display");
}
#endif
return router::send(module::Lcd, task::DisplayDriverPrimary);
}
int Cmd::handleBatteryCal(unsigned short argc, char *argv[]) {
if (argc != 2) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("BATTERY_CAL expects 1 argument");
}
#endif
return 1;
}
float vbat = strtod(argv[1], nullptr);
uint32_t task_data;
memcpy(&task_data, &vbat, sizeof(uint32_t));
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Calibrating VBAT");
}
#endif
router::send(module::Battery, task::BatteryCal, task_data);
return 0;
}
int Cmd::handleBatteryPrintVbat(unsigned short argc) {
if (argc != 1) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("BATTERY_PRINT_VBAT expects no arguments");
}
#endif
return 1;
}
#ifdef INFO
float vbat;
vbatGlobalRead(vbat);
if (logger_ != nullptr) {
logger_->info("VBAT: " + String(vbat));
}
#endif
return 0;
}
int Cmd::handleBatterySetLow(unsigned short argc, char* argv[]) {
if (argc != 2) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("BATTERY_SET_LOW expects 1 argument");
}
#endif
return 1;
}
float low = strtod(argv[1], nullptr);
uint32_t task_data;
memcpy(&task_data, &low, sizeof(uint32_t));
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Setting warning level for VBAT");
}
#endif
router::send(module::Config, task::ConfigVbatSetLow, task_data);
return 0;
}
int Cmd::handleThermoSetLow(unsigned short argc, char* argv[]) {
if (argc != 2) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("THERMO_SET_LOW expects 1 argument");
}
#endif
return 1;
}
float low = strtod(argv[1], nullptr);
uint32_t task_data;
memcpy(&task_data, &low, sizeof(uint32_t));
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Setting low level for TENG");
}
#endif
router::send(module::Config, task::ConfigTengSetLow, task_data);
return 0;
}
int Cmd::handleThermoSetHigh(unsigned short argc, char* argv[]) {
if (argc != 2) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("THERMO_SET_HIGH expects 1 argument");
}
#endif
return 1;
}
float low = strtod(argv[1], nullptr);
uint32_t task_data;
memcpy(&task_data, &low, sizeof(uint32_t));
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Setting high level for TENG");
}
#endif
router::send(module::Config, task::ConfigTengSetHigh, task_data);
return 0;
}
int Cmd::handleUnknownCommand(unsigned short argc, char *argv[]) {
#ifdef ERROR
if (logger_ != nullptr) {
if (argc > 0 && argv != nullptr && argv[0] != nullptr && argv[0][0] != '\0') {
logger_->error(String("Unknown command: ") + String(argv[0]));
} else {
logger_->error("Unknown command");
}
}
#endif
return 1;
}
int Cmd::dispatchCommand(CommandId command, unsigned short argc, char *argv[]) {
switch (command) {
case Reboot:
return this->handleRebootCommand(argc);
case ConfigDump:
return this->handleDumpConfigCommand(argc);
case PutTrack:
return this->handleTrackPutCommand(argc, argv);
case DeleteTrack:
return this->handleTrackDeleteCommand(argc, argv);
case DumpTrack:
return this->handleTrackDumpCommand(argc, argv);
case ConfigReset:
return this->handleConfigResetCommand(argc);
case TrackAutodetect:
return this->handleTrackAutodetectCommand(argc);
case DisplayGpsDebug:
return this->handleDisplayGpsDebug(argc);
case DisplayDriverPrimary:
return this->handleDisplayDriverPrimary(argc);
case BatteryCal:
return this->handleBatteryCal(argc, argv);
case BatteryPrintVbat:
return this->handleBatteryPrintVbat(argc);
case BatterySetLow:
return this->handleBatterySetLow(argc, argv);
case ThermoSetLow:
return this->handleThermoSetLow(argc, argv);
case ThermoSetHigh:
return this->handleThermoSetHigh(argc, argv);
case Unknown:
default:
return this->handleUnknownCommand(argc, argv);
}
}
int Cmd::tryParse() {
#ifdef DEBUG
if (logger_ != nullptr) {
logger_->debug("Attempting to parse command");
}
#endif
char *argvp[MAX_ARGS];
unsigned short argc = splitArgs(buffer_, argvp, MAX_ARGS);
if (argc == 0 || argvp[0] == nullptr || argvp[0][0] == '\0') {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("Empty command");
}
#endif
return 1;
}
CommandId command = parseCommandName(argvp[0]);
return dispatchCommand(command, argc, argvp);
}
int Cmd::push(const Task &task) {
return queue_.push(task);
}
Cmd::Cmd(HardwareSerial *data_stream)
: data_stream_(data_stream), logger_(nullptr) {}
Cmd::Cmd(HardwareSerial *data_stream, SystemLogger *logger)
: data_stream_(data_stream), logger_(logger) {}
Cmd::~Cmd() {}
int Cmd::init() {
data_stream_->begin(baud_rate_);
return 0;
}
int Cmd::parseTask(unsigned long timeout_ms) {
unsigned long start = millis();
while (data_stream_->available()) {
if ((unsigned long)(millis() - start) >= timeout_ms) {
return 1;
}
char current_char = data_stream_->read();
if (current_char == '<') {
buffer_open_ = true;
index_ = 0;
continue;
}
if (!buffer_open_) {
continue;
}
if (current_char == '>') {
buffer_[index_] = '\0';
buffer_open_ = false;
return this->tryParse();
}
if (index_ >= sizeof(buffer_) - 1) {
buffer_open_ = false;
index_ = 0;
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("Command parser buffer overflow");
}
#endif
return 1;
}
buffer_[index_] = current_char;
index_++;
}
return 0;
}

76
src/modules/cmd/cmd.h Normal file
View File

@@ -0,0 +1,76 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <Arduino.h>
#include <avr/wdt.h>
#include "base/module_base.h"
#include "base/ring_buffer.h"
#include "base/task.h"
#include "custom_types.h"
#include "modules/logger/system_logger.h"
class Cmd : public ModuleBase {
private:
enum CommandId {
Unknown = 0,
Reboot,
PutTrack,
DeleteTrack,
DumpTrack,
ConfigReset,
ConfigDump,
TrackAutodetect,
DisplayGpsDebug,
DisplayGpsLineDebug,
DisplayDriverPrimary,
BatteryCal,
BatteryPrintVbat,
BatterySetLow,
ThermoSetLow,
ThermoSetHigh,
};
HardwareSerial *data_stream_;
unsigned long baud_rate_ = 115200;
SystemLogger *logger_;
char buffer_[256];
unsigned int index_ = 0;
bool buffer_open_ = false;
RingBuffer<Task, 16> queue_;
static const unsigned short MAX_ARGS = 10;
int tryParse();
unsigned short splitArgs(char *input, char *argv[], unsigned short max_args);
char *trimArg(char *input);
CommandId parseCommandName(const char *input);
int dispatchCommand(CommandId command, unsigned short argc, char *argv[]);
int parseTrackSlotId(const char *id_str, unsigned short &id_out);
int dumpTrackSlot(unsigned short id);
int handleRebootCommand(unsigned short argc);
int handleDumpConfigCommand(unsigned short argc);
int handleTrackPutCommand(unsigned short argc, char *argv[]);
int handleTrackDeleteCommand(unsigned short argc, char *argv[]);
int handleTrackDumpCommand(unsigned short argc, char *argv[]);
int handleConfigResetCommand(unsigned short argc);
int handleTrackAutodetectCommand(unsigned short argc);
int handleDisplayGpsDebug(unsigned short argc);
int handleDisplayDriverPrimary(unsigned short argc);
int handleBatteryCal(unsigned short argc, char *argv[]);
int handleBatteryPrintVbat(unsigned short argc);
int handleBatterySetLow(unsigned short argc, char *argv[]);
int handleThermoSetLow(unsigned short argc, char *argv[]);
int handleThermoSetHigh(unsigned short argc, char *argv[]);
int handleUnknownCommand(unsigned short argc, char *argv[]);
public:
int push(const Task &task) override;
Cmd(HardwareSerial *data_stream);
Cmd(HardwareSerial *data_stream, SystemLogger *logger);
~Cmd();
int init();
int parseTask(unsigned long timeout_ms = 500);
};

View File

@@ -0,0 +1,396 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "config.h"
#include "data/track_store.h"
#include <math.h>
#include <string.h>
int Config::push(const Task &task) { return queue_.push(task); }
int Config::taskComplete() {
task_memory_stale_ = true;
active_task_ = Task(module::Null, task::Null, 0);
return 0;
}
int Config::writeTrack(const TrackData &track_data) {
TrackData track_copy = track_data;
track_copy.magic_ = CONFIG_MAGIC;
if (track_copy.id_ < 1 || track_copy.id_ > 8) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("Cannot write track data with out of range id, aborting");
}
#endif
return 1;
}
EEPROM.put(eeprom_layout::trackSlotAddr(track_copy.id_), track_copy);
config_.track_slot_occupied_[track_copy.id_ - 1] = true;
this->writeConfig();
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Succesfully wrote new track into slot " + String(track_copy.id_));
}
#endif
return 0;
}
int Config::writeTrackFromTemp() {
TrackData track_data;
trackTempGlobalRead(track_data);
return this->writeTrack(track_data);
}
int Config::deleteTrack(unsigned short idx) {
if (idx < 1 || idx > 8) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("Cannot delete track with out of range id, aborting");
}
#endif
return 1;
}
if (config_.track_slot_occupied_[idx - 1] == false) {
#ifdef WARN
if (logger_ != nullptr) {
logger_->warn("Requested delete on empty track slot " + String(idx));
}
#endif
return 0;
}
config_.track_slot_occupied_[idx - 1] = false;
if (is_track_loaded_ && loaded_track_.id_ == idx) {
is_track_loaded_ = false;
loaded_track_ = {};
GlobalTrackData track;
track.loaded_ = false;
track.root_ = loaded_track_;
trackGlobalWrite(track);
}
int write_result = this->writeConfig();
#ifdef INFO
if (logger_ != nullptr && write_result == 0) {
logger_->info("Succesfully deleted track slot " + String(idx));
}
#endif
return write_result;
}
int Config::resetConfig() {
VehicleConfig clean_config;
config_ = clean_config;
is_track_loaded_ = false;
loaded_track_ = {};
task_memory_stale_ = true;
no_tracks_notice_shown_ = false;
GlobalTrackData track;
track.loaded_ = false;
track.root_ = loaded_track_;
trackGlobalWrite(track);
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Resetting configuration to factory defaults");
}
#endif
return this->writeConfig();
}
int Config::writeVbatCal(float value) {
config_.vbat_calibration_ = value;
return this->writeConfig();
}
int Config::writeVbatLow(float value) {
config_.vbat_low_ = value;
return this->writeConfig();
}
int Config::writeTengLow(float value) {
config_.teng_low_ = value;
return this->writeConfig();
}
int Config::writeTengHigh(float value) {
config_.teng_high_ = value;
return this->writeConfig();
}
Config::Config() : logger_(nullptr), valid_config_(true) {}
Config::Config(SystemLogger *logger) : logger_(logger), valid_config_(true) {}
Config::~Config() {}
int Config::readConfig() {
EEPROM.get(eeprom_layout::CONFIG_ADDR, config_);
configGlobalWrite(config_);
return 0;
}
int Config::writeConfig() {
EEPROM.put(eeprom_layout::CONFIG_ADDR, config_);
configGlobalWrite(config_);
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Config updated and saved to EEPROM");
}
#endif
router::send(module::All, task::AllConfigUpdated);
return 0;
}
int Config::writeConfig(const VehicleConfig &new_config) {
config_ = new_config;
EEPROM.put(eeprom_layout::CONFIG_ADDR, new_config);
configGlobalWrite(new_config);
return 0;
}
int Config::taskConfigDetectTrack(unsigned long timeout_ms) {
unsigned long start = millis();
bool has_at_least_one_track = false;
for (size_t i = 0; i < 8; i++) {
if (config_.track_slot_occupied_[i] == true) {
has_at_least_one_track = true;
break;
}
}
if (!has_at_least_one_track) {
if (!no_tracks_notice_shown_) {
router::send(module::Lcd, task::DisplayMsgConfigNoTracks, 3000);
no_tracks_notice_shown_ = true;
}
this->taskComplete();
return 1;
}
TaskConfigTrackDetectData task_data;
if (!task_memory_stale_) {
memcpy(&task_data, task_memory_, sizeof(task_data));
} else {
GpsData current_gps;
gpsGlobalRead(current_gps);
task_data.gps_lat_ = current_gps.lat_.value_;
task_data.gps_lng_ = current_gps.lng_.value_;
task_data.cos_ = cos(task_data.gps_lat_ * M_PI / 180);
}
while (true) {
task_data.last_checked_++;
TrackData track_data;
int result = this->getTrack(task_data.last_checked_, track_data);
if (result == 0) {
float delta_lat = track_data.point_a_.lat_ - task_data.gps_lat_;
float delta_lng = (track_data.point_a_.lng_ - task_data.gps_lng_) * task_data.cos_;
float dist2 = delta_lat * delta_lat + delta_lng * delta_lng;
if (dist2 < task_data.sqdiff_ || task_data.smallest_idx_ == 0) {
task_data.smallest_idx_ = task_data.last_checked_;
task_data.sqdiff_ = dist2;
}
}
if (task_data.last_checked_ >= 8) {
int load_result = 1;
if (task_data.smallest_idx_ > 0) {
load_result = this->loadTrack(task_data.smallest_idx_);
}
this->taskComplete();
if (load_result == 0) {
no_tracks_notice_shown_ = false;
#ifdef INFO
if (logger_ != nullptr) {
logger_->info("Track detected: " + String(loaded_track_.name_));
}
#endif
router::send(module::Lcd, task::DisplayMsgTrackDetectOk, 4000);
return 0;
}
if (!no_tracks_notice_shown_) {
router::send(module::Lcd, task::DisplayMsgConfigNoTracks, 3000);
no_tracks_notice_shown_ = true;
}
return 1;
}
if ((unsigned long)(millis() - start) >= timeout_ms) {
task_memory_stale_ = false;
memcpy(task_memory_, &task_data, sizeof(task_data));
return 1;
}
}
}
int Config::handleActiveTask(unsigned long timeout_ms) {
switch (active_task_.type_) {
case task::ConfigTrackDetect: {
if (!is_track_loaded_ || active_task_.data_ == 1) {
#ifdef DEBUG
if (logger_ != nullptr) {
logger_->debug("Detect track called");
}
#endif
return taskConfigDetectTrack(timeout_ms);
}
this->taskComplete();
return 0;
}
case task::ConfigWriteTempTrack: {
int result = this->writeTrackFromTemp();
this->taskComplete();
return result;
}
case task::ConfigTrackDelete: {
int result = this->deleteTrack(active_task_.data_);
this->taskComplete();
return result;
}
case task::ConfigReset: {
int result = this->resetConfig();
this->taskComplete();
return result;
}
case task::ConfigVbatCalSet: {
float cal_value;
memcpy(&cal_value, &active_task_.data_, sizeof(float));
int result = this->writeVbatCal(cal_value);
this->taskComplete();
return result;
}
case task::ConfigVbatSetLow: {
float low_value;
memcpy(&low_value, &active_task_.data_, sizeof(float));
int result = this->writeVbatLow(low_value);
this->taskComplete();
return result;
}
case task::ConfigTengSetLow: {
float low_value;
memcpy(&low_value, &active_task_.data_, sizeof(float));
int result = this->writeTengLow(low_value);
this->taskComplete();
return result;
}
case task::ConfigTengSetHigh: {
float high_value;
memcpy(&high_value, &active_task_.data_, sizeof(float));
int result = this->writeTengHigh(high_value);
this->taskComplete();
return result;
}
default:
break;
}
return 0;
}
int Config::autoInit() {
this->readConfig();
if (config_.magic_ != CONFIG_MAGIC) {
#ifdef WARN
if (logger_ != nullptr) {
logger_->warn("Config invalid, overwriting");
}
#endif
VehicleConfig clean_config;
this->writeConfig(clean_config);
this->readConfig();
if (config_.magic_ != CONFIG_MAGIC) {
#ifdef ERROR
if (logger_ != nullptr) {
logger_->error("Config write failed, EEPROM may be burnt");
}
#endif
return 1;
}
}
valid_config_ = true;
return 0;
}
int Config::loop(unsigned long timeout_ms) {
if (active_task_.type_ != task::Null && active_task_.target_ != module::Null) {
this->handleActiveTask(timeout_ms);
return 0;
}
int result = queue_.pop(active_task_);
if (result == 0) {
this->handleActiveTask(timeout_ms);
}
return 0;
}
int Config::getTrack(unsigned int idx, TrackData &track_data) {
if (idx < 1 || idx > 8) {
return 1;
}
if (config_.track_slot_occupied_[idx - 1] == false) {
return 1;
}
EEPROM.get(eeprom_layout::trackSlotAddr(idx), track_data);
if (track_data.magic_ != CONFIG_MAGIC) {
return 1;
}
return 0;
}
int Config::loadTrack(unsigned int idx) {
if (idx < 1 || idx > 8) {
return 1;
}
if (config_.track_slot_occupied_[idx - 1] == false) {
return 1;
}
TrackData track_data;
EEPROM.get(eeprom_layout::trackSlotAddr(idx), track_data);
if (track_data.magic_ != CONFIG_MAGIC) {
return 1;
}
loaded_track_ = track_data;
GlobalTrackData track;
track.loaded_ = true;
Vec2 point_b =eqRectProjection(track_data.point_b_, track_data.point_a_);
track.center_ = vec2Midpoint(point_b, (Vec2){0.0f,0.0f});
float radius = max(10.0f, vecMod(point_b) * 1.25f);
track.circle_radius_sq_ = radius*radius;
track.root_ = track_data;
trackGlobalWrite(track);
is_track_loaded_ = true;
router::send(module::All, task::AllTrackLoaded);
return 0;
}

View File

@@ -0,0 +1,64 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "base/module_base.h"
#include "base/ring_buffer.h"
#include "base/task.h"
#include "custom_types.h"
#include "flags.h"
#include "modules/logger/system_logger.h"
#include <EEPROM.h>
#include "data/gps_store.h"
#include "data/track_store.h"
#include "data/eeprom_layout.h"
#include "base/router.h"
struct TaskConfigTrackDetectData {
unsigned short last_checked_ = 0;
unsigned short smallest_idx_ = 0;
float cos_ = 0;
float sqdiff_ = 0;
float gps_lat_ = 0;
float gps_lng_ = 0;
};
class Config : public ModuleBase {
private:
VehicleConfig config_;
SystemLogger *logger_;
bool valid_config_;
TrackData loaded_track_;
bool is_track_loaded_ = false;
RingBuffer<Task, 16> queue_;
Task active_task_ = {};
uint8_t task_memory_[64] = {};
bool task_memory_stale_ = true;
bool no_tracks_notice_shown_ = false;
int readConfig();
int writeConfig();
int writeConfig(const VehicleConfig &new_config);
int handleActiveTask(unsigned long timeout_ms);
int taskConfigDetectTrack(unsigned long timeout_ms);
int taskComplete();
int writeTrack(const TrackData& track_data);
int writeTrackFromTemp();
int deleteTrack(unsigned short idx);
int resetConfig();
int writeVbatCal(float value);
int writeVbatLow(float value);
int writeTengLow(float value);
int writeTengHigh(float value);
public:
int push(const Task &task) override;
Config();
Config(SystemLogger *logger);
~Config();
int autoInit();
int loop(unsigned long timeout_ms = 500);
int getTrack(unsigned int idx, TrackData &track_data);
int loadTrack(unsigned int idx);
};

186
src/modules/gps/gps.cpp Normal file
View File

@@ -0,0 +1,186 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "gps.h"
#include "math.h"
#include "data/track_store.h"
#define MOD "modules/gps/gps.h"
int Gps::push(const Task &task) { return queue_.push(task); }
Gps::Gps(HardwareSerial *data_stream)
: gps_(nullptr), data_stream_(data_stream), logger_(nullptr) {
gps_ = new TinyGPSPlus();
}
Gps::Gps(HardwareSerial *data_stream, SystemLogger *logger)
: gps_(nullptr), data_stream_(data_stream), logger_(logger) {
gps_ = new TinyGPSPlus();
}
Gps::~Gps() {
data_stream_ = nullptr;
delete gps_;
gps_ = nullptr;
}
int Gps::init() {
data_stream_->begin(9600);
return 0;
}
int Gps::loop(unsigned long timeout_ms) {
unsigned long timeout = millis() + timeout_ms;
bool timed_out = false;
while (data_stream_->available() > 0) {
if (gps_->encode(data_stream_->read())) {
gpsGlobalWrite(this->getData());
uint32_t current_fix_value = gps_->sentencesWithFix();
if (last_fix_value_ == 0 && current_fix_value > 0) {
router::send(module::Lcd, task::DisplayMsgGpsFix, 2000);
router::send(module::Config, task::ConfigTrackDetect);
router::send(module::All, task::AllGpsFixOk);
}
last_fix_value_ = current_fix_value;
}
if (millis() > timeout) {
timed_out = true;
break;
}
}
Task active;
int res = queue_.pop(active);
if (res == 0) {
if (active.target_ == module::Gps) {
} else if (active.target_ == module::All) {
switch (active.type_) {
case task::AllTrackLoaded: {
#ifdef DEBUG
if (logger_ != nullptr) {
logger_->debug("GPS received track loaded sig");
}
#endif
GlobalTrackData track;
trackGlobalRead(track);
lap_active_ = track.loaded_;
start_line_trigger_ = trigger_status::Idle;
gpsTriggerGlobalWrite(start_line_trigger_);
arm_sign_ = 0;
if (!track.loaded_) {
break;
}
track_point_a_ = track.root_.point_a_;
track_point_b_ = track.root_.point_b_;
track_vec_b_ = eqRectProjection(track_point_b_, track_point_a_);
track_vec_center_ = track.center_;
start_line_length_ = vecMod(track_vec_b_);
start_line_sq_dist_ = track.circle_radius_sq_;
break;
}
default:
break;
}
}
}
if (lap_active_ && millis() - last_check_ > check_interval_) {
unsigned long now = millis();
GpsData gps;
gpsGlobalRead(gps);
LatLng vehicle_position = {gps.lat_.value_, gps.lng_.value_};
Vec2 vehicle_pos_vec = eqRectProjection(vehicle_position, track_point_a_);
float center_dist_sq = vec2SqDist(track_vec_center_, vehicle_pos_vec);
float cross = vec2Cross(track_vec_b_, vehicle_pos_vec);
int sign = 0;
if (cross < 0) {
sign = -1;
} else if (cross > 0) {
sign = 1;
}
switch (start_line_trigger_) {
case trigger_status::Idle: {
if (center_dist_sq < start_line_sq_dist_) {
start_line_trigger_ = trigger_status::Armed;
gpsTriggerGlobalWrite(start_line_trigger_);
arm_sign_ = sign;
state_changed_at_ = now;
}
break;
};
case trigger_status::Armed: {
if (center_dist_sq > start_line_sq_dist_) {
start_line_trigger_ = trigger_status::Idle;
gpsTriggerGlobalWrite(start_line_trigger_);
arm_sign_ = 0;
state_changed_at_ = 0;
} else if ((sign == -1 && arm_sign_ == 1) || (sign == 1 && arm_sign_ == -1)) {
start_line_trigger_ = trigger_status::Trigd;
gpsTriggerGlobalWrite(start_line_trigger_);
arm_sign_ = 0;
state_changed_at_ = now;
router::send(module::All, task::AllStartLineTriggered);
}
break;
};
case trigger_status::Trigd: {
if (center_dist_sq > start_line_sq_dist_) {
start_line_trigger_ = trigger_status::Idle;
gpsTriggerGlobalWrite(start_line_trigger_);
arm_sign_ = 0;
state_changed_at_ = now;
}
break;
};
default:
break;
}
last_check_ = now;
}
return 0;
}
GpsData Gps::getData() {
GpsData output;
output.altitude_.age_ = gps_->altitude.age();
output.altitude_.valid_ = gps_->altitude.isValid();
output.altitude_.value_ = gps_->altitude.meters();
output.lat_.age_ = gps_->location.age();
output.lat_.valid_ = gps_->location.isValid();
output.lat_.value_ = gps_->location.lat();
output.lng_.age_ = gps_->location.age();
output.lng_.valid_ = gps_->location.isValid();
output.lng_.value_ = gps_->location.lng();
output.speed_.age_ = gps_->speed.age();
output.speed_.valid_ = gps_->speed.isValid();
output.speed_.value_ = gps_->speed.kmph();
output.course_.age_ = gps_->course.age();
output.course_.valid_ = gps_->course.isValid();
output.course_.value_ = gps_->course.deg();
output.time_ = gps_->time.value();
output.time_write_time_ = millis() - gps_->time.age();
output.num_fix_ = gps_->sentencesWithFix();
return output;
}
#undef MOD

57
src/modules/gps/gps.h Normal file
View File

@@ -0,0 +1,57 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "custom_types.h"
#include "TinyGPSPlus.h"
#include "flags.h"
#include "modules/logger/system_logger.h"
#include "base/task.h"
#include "base/ring_buffer.h"
#include "base/module_base.h"
#include "data/gps_store.h"
#include "data/general_store.h"
#include "base/router.h"
namespace trigger_status {
enum TriggerStatus {
Idle = 0,
Armed = 1,
Trigd = 2,
};
}
class Gps : public ModuleBase {
private:
TinyGPSPlus *gps_;
HardwareSerial *data_stream_;
SystemLogger *logger_;
RingBuffer<Task, 16> queue_;
uint32_t last_fix_value_ = 0;
trigger_status::TriggerStatus start_line_trigger_ = trigger_status::Idle;
LatLng track_point_a_;
LatLng track_point_b_;
Vec2 track_vec_b_;
Vec2 track_vec_center_;
float start_line_length_ = 0;
float start_line_sq_dist_ = 0;
bool lap_active_ = false;
unsigned long last_check_ = 0;
unsigned long check_interval_ = 100;
unsigned long state_changed_at_ = 0;
int arm_sign_ = 0;
public:
int push(const Task &task) override;
Gps(HardwareSerial *data_stream);
Gps(HardwareSerial *data_stream, SystemLogger *logger);
~Gps();
int loop(unsigned long timeout_ms = 500);
int init();
GpsData getData();
};

View File

@@ -0,0 +1,45 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "injection_counter.h"
#include "base/router.h"
#include "data/general_store.h"
int InjectionCounter::push(const Task &task) { return queue_.push(task); }
InjectionCounter::InjectionCounter() : logger_(nullptr) {};
InjectionCounter::InjectionCounter(SystemLogger *logger) : logger_(logger) {};
InjectionCounter::~InjectionCounter() {};
int InjectionCounter::init() { pinMode(INJ_GPIO, INPUT); }
int InjectionCounter::loop() {
unsigned long now = millis();
if (now - last_check_ >= check_interval_) {
last_check_ = now;
int val = digitalRead(INJ_GPIO);
if (val == 1 && last_switch_ == 0 && !waiting_debounce_) {
waiting_debounce_ = true;
last_switch_time_ = now;
}
if (waiting_debounce_) {
if (now - last_switch_time_ >= debounce_) {
if (digitalRead(INJ_GPIO) == 1) {
counter_++;
injectionCtrGlobalWrite(counter_);
}
waiting_debounce_ = false;
}
}
last_switch_ = val;
}
return 0;
}

View File

@@ -0,0 +1,30 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "base/module_base.h"
#include "base/ring_buffer.h"
#include "modules/logger/system_logger.h"
#define INJ_GPIO 37
class InjectionCounter : public ModuleBase {
private:
SystemLogger *logger_;
RingBuffer<Task, 16> queue_;
unsigned long last_check_;
unsigned long check_interval_ = 100;
unsigned long debounce_ = 100;
int last_switch_ = 0;
int last_switch_time_ = 0;
bool waiting_debounce_ = 0;
uint16_t counter_ = 0;
public:
int push(const Task &task) override;
InjectionCounter();
InjectionCounter(SystemLogger* logger);
~InjectionCounter();
int init();
int loop();
};

View File

@@ -0,0 +1,109 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "lap_counter.h"
#include "base/router.h"
#include "custom_types.h"
#include "data/general_store.h"
#include "data/gps_store.h"
#include "data/track_store.h"
int LapCounter::push(const Task &task) { return queue_.push(task); }
LapCounter::LapCounter() : logger_(nullptr) {};
LapCounter::LapCounter(SystemLogger *logger) : logger_(logger) {};
LapCounter::~LapCounter() {}
int LapCounter::init() {
counting_ = false;
count_ = false;
return 0;
}
int LapCounter::loop() {
Task active_task;
int res = queue_.pop(active_task);
if (res == 0) {
if (active_task.target_ == module::LapCounter) {
} else if (active_task.target_ == module::All) {
switch (active_task.type_) {
case task::AllStartLineTriggered: {
GpsData gps;
gpsGlobalRead(gps);
uint32_t base_cs = hhmmsscc_to_cs(gps.time_);
uint32_t elapsed_cs = (millis() - gps.time_write_time_) / 10;
uint32_t time_cs = base_cs + elapsed_cs;
if (!counting_) {
counting_ = true;
last_trigger_time_ = time_cs;
router::send(module::Lcd, task::DisplayMsgLapCounterStart, 1000);
} else {
uint32_t lap_time = time_cs - last_trigger_time_;
lap_times_idx_ = (lap_times_idx_ + 1) & 63;
lap_times_[lap_times_idx_] = lap_time;
count_++;
lapCountGlobalWrite(count_);
last_trigger_time_ = time_cs;
lastLapTimeGlobalWrite(lap_time);
router::send(module::Lcd, task::DisplayMsgLapCounterLapTime, 1000);
}
break;
}
case task::AllGpsFixOk: {
average_enabled_ = true;
#ifdef DEBUG
if (logger_ != nullptr) {
logger_->debug("Enabled average counter");
}
#endif
break;
}
default:
break;
}
}
}
if (millis() - last_average_time_ > average_loop_time_ && average_enabled_) {
GpsData gps;
gpsGlobalRead(gps);
unsigned long now = millis();
float dt = (now - last_average_time_) / 1000.0f;
float speed = gps.speed_.value_;
if (speed < 1) speed = 0;
continuous_time_sum_ += dt;
if (last_average_time_ == 0) {
continuous_speed_sum_ += speed * dt;
} else {
continuous_speed_sum_ +=
(speed + previous_speed_) * 0.5f * dt;
}
previous_speed_ = speed;
speedAvgGlobalWrite(continuous_speed_sum_ / continuous_time_sum_);
last_average_time_ = now;
}
return 0;
}

View File

@@ -0,0 +1,40 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "base/module_base.h"
#include "base/ring_buffer.h"
#include "custom_types.h"
#include "modules/logger/system_logger.h"
#include <inttypes.h>
class LapCounter : public ModuleBase {
private:
SystemLogger *logger_;
RingBuffer<Task, 16> queue_;
bool counting_ = false;
uint16_t count_ = 0;
uint32_t last_trigger_time_ = 0;
uint32_t lap_times_[64];
int16_t lap_times_idx_ = -1;
bool average_enabled_ = false;
unsigned long average_loop_time_ = 250;
unsigned long last_average_time_ = 0;
float continuous_speed_sum_ = 0;
float lap_speed_sum_ = 0;
float continuous_time_sum_ = 0;
float lap_time_sum_ = 0;
float previous_speed_ = 0;
public:
int push(const Task &task) override;
LapCounter();
LapCounter(SystemLogger *logger);
~LapCounter();
int init();
int loop();
};

680
src/modules/lcd/lcd.cpp Normal file
View File

@@ -0,0 +1,680 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "lcd.h"
#include "data/general_store.h"
#include "modules/gps/gps.h"
#include <Wire.h>
#include <string.h>
#define MOD "modules/lcd/lcd.h"
void Lcd::clear() {
if (!display_cleared_) {
display_->clear();
display_cleared_ = true;
}
}
void Lcd::print(const String &msg) {
display_->print(msg);
display_cleared_ = false;
}
void Lcd::print(char c) {
display_->print(c);
display_cleared_ = false;
}
void Lcd::print(const char c[]) {
display_->print(c);
display_cleared_ = false;
}
void Lcd::print(float d, int digits) {
display_->print(d, digits);
display_cleared_ = false;
}
void Lcd::print(unsigned long l, int base) {
display_->print(l, base);
display_cleared_ = false;
}
void Lcd::print(long l, int base) {
display_->print(l, base);
display_cleared_ = false;
}
void Lcd::print(unsigned int i, int base) {
display_->print(i, base);
display_cleared_ = false;
}
void Lcd::print(int i, int base) {
display_->print(i, base);
display_cleared_ = false;
}
bool Lcd::isMessageTask(task::Type type) {
switch (type) {
case task::DisplayMsgGpsFix:
case task::DisplayMsgTrackDetectOk:
case task::DisplayMsgConfigNoTracks:
case task::DisplayMsgBatteryLow:
case task::DisplayMsgEngineTempLow:
case task::DisplayMsgEngineTempHigh:
case task::DisplayMsgLapCounterLapTime:
case task::DisplayMsgLapCounterStart:
return true;
default:
return false;
}
}
void Lcd::activateMessage(screen::LcdScreen msg_screen,
unsigned long duration_ms) {
if (duration_ms == 0) {
duration_ms = frame_duration_;
}
message_screen_ = msg_screen;
message_active_ = true;
message_end_ = millis() + duration_ms;
screen_ = message_screen_;
force_render_ = true;
}
void Lcd::expireMessageIfNeeded(unsigned long now) {
if (!message_active_) {
return;
}
if ((long)(now - message_end_) >= 0) {
message_active_ = false;
message_screen_ = screen::Blank;
screen_ = data_screen_;
force_render_ = true;
base_rendered_ = false;
}
}
screen::LcdScreen Lcd::getActiveScreen() const {
if (message_active_) {
return message_screen_;
}
return data_screen_;
}
int Lcd::renderGpsDebug() {
this->clear();
GpsData gps_data;
gpsGlobalRead(gps_data);
display_->setCursor(0, 0);
this->print("Alt: ");
if (gps_data.altitude_.valid_) {
this->print(gps_data.altitude_.value_, 5);
} else {
this->print("not valid");
}
display_->setCursor(0, 1);
this->print("Lat: ");
if (gps_data.lat_.valid_) {
this->print(gps_data.lat_.value_, 5);
} else {
this->print("not valid");
}
display_->setCursor(0, 2);
this->print("Lng: ");
if (gps_data.lng_.valid_) {
this->print(gps_data.lng_.value_, 5);
} else {
this->print("not valid");
}
display_->setCursor(0, 3);
this->print("Spd: ");
if (gps_data.speed_.valid_) {
this->print(gps_data.speed_.value_, 5);
} else {
this->print("not valid");
}
return 0;
}
int Lcd::renderDriverPrimary() {
GpsData gps_data;
gpsGlobalRead(gps_data);
float vbat;
vbatGlobalRead(vbat);
float teng;
tengGlobalRead(teng);
int line_trigger;
gpsTriggerGlobalRead(line_trigger);
uint16_t num_laps;
lapCountGlobalRead(num_laps);
float average_speed;
speedAvgGlobalRead(average_speed);
uint16_t inj_ctr;
injectionCtrGlobalRead(inj_ctr);
if (!base_rendered_) {
this->clear();
display_->setCursor(0, 0);
this->print("GPS:");
display_->setCursor(7, 0);
this->print("LAPS:");
display_->setCursor(0, 1);
this->print("INJ:");
display_->setCursor(0, 2);
this->print("SPD:");
display_->setCursor(10, 2);
this->print("AVG:");
display_->setCursor(0, 3);
this->print("V:");
display_->setCursor(10, 3);
this->print("T:");
base_rendered_ = true;
}
display_->setCursor(4, 0);
if (gps_data.num_fix_ != 0) {
this->print("Y");
} else {
this->print("N");
}
display_->setCursor(12, 0);
if (num_laps < 10)
this->print('0');
this->print(num_laps, 10);
display_->setCursor(4, 1);
if (inj_ctr < 100) {
this->print('0');
if (inj_ctr < 10) {
this->print('0');
}
}
this->print(inj_ctr, 10);
display_->setCursor(4, 2);
if (gps_data.speed_.value_ < 10.0)
this->print('0');
this->print(gps_data.speed_.value_, 1);
display_->setCursor(14, 2);
if (average_speed < 10.0)
this->print('0');
this->print(average_speed, 1);
display_->setCursor(2, 3);
this->print(vbat, 1);
display_->setCursor(12, 3);
this->print(teng, 1);
return 0;
}
int Lcd::renderMsgGpsFix() {
if (!base_rendered_) {
this->clear();
display_->setCursor(6, 1);
this->print("GPS INFO");
display_->setCursor(7, 2);
this->print("FIX OK");
base_rendered_ = true;
}
return 0;
}
int Lcd::renderMsgGpsTrigger() {
if (!base_rendered_) {
this->clear();
display_->setCursor(6, 1);
this->print("GPS INFO");
display_->setCursor(4, 2);
this->print("LINE TRIGGER");
base_rendered_ = true;
}
return 0;
}
int Lcd::renderMsgTrackDetectOk() {
if (!base_rendered_) {
this->clear();
display_->setCursor(6, 0);
this->print("GPS INFO");
display_->setCursor(3, 1);
this->print("TRACK DETECTED");
GlobalTrackData track_data;
trackGlobalRead(track_data);
display_->setCursor((20 - strlen(track_data.root_.name_)) / 2, 2);
this->print(track_data.root_.name_);
base_rendered_ = true;
}
return 0;
}
int Lcd::renderMsgConfigNoTracks() {
if (!base_rendered_) {
this->clear();
display_->setCursor(4, 1);
this->print("CONFIG INFO");
display_->setCursor(2, 2);
this->print("NO TRACKS LOADED");
base_rendered_ = true;
}
return 0;
}
int Lcd::renderMsgBatteryLow() {
if (!base_rendered_) {
this->clear();
display_->setCursor(6, 1);
this->print("WARNING");
display_->setCursor(6, 2);
this->print("VBAT LOW");
base_rendered_ = true;
}
return 0;
}
int Lcd::renderMsgEngineTempLow() {
if (!base_rendered_) {
this->clear();
display_->setCursor(6, 1);
this->print("WARNING");
display_->setCursor(2, 2);
this->print("ENGINE TEMP LOW");
base_rendered_ = true;
}
return 0;
}
int Lcd::renderMsgEngineTempHigh() {
if (!base_rendered_) {
this->clear();
display_->setCursor(6, 1);
this->print("WARNING");
display_->setCursor(2, 2);
this->print("ENGINE TEMP HIGH");
base_rendered_ = true;
}
return 0;
}
int Lcd::renderMsgLapCounterStart() {
if (!base_rendered_) {
this->clear();
display_->setCursor(5, 1);
this->print("LAP COUNTER");
display_->setCursor(6, 2);
this->print("STARTED");
base_rendered_ = true;
}
return 0;
}
int Lcd::renderMsgLapCounterLapTime() {
if (!base_rendered_) {
uint32_t time_cs;
lastLapTimeGlobalRead(time_cs);
uint32_t minutes = (time_cs / 6000);
uint32_t seconds = (time_cs / 100) % 60;
uint32_t cs = time_cs % 100;
this->clear();
display_->setCursor(6, 1);
this->print("LAP TIME");
display_->setCursor(6, 2);
if (minutes < 10)
this->print('0');
this->print(minutes, 10);
this->print(':');
if (seconds < 10)
this->print('0');
this->print(seconds, 10);
this->print('.');
if (cs < 10)
this->print('0');
this->print(cs, 10);
base_rendered_ = true;
}
return 0;
}
int Lcd::push(const Task &task) { return queue_.push(task); }
Lcd::Lcd()
: display_cleared_(false), logger_(nullptr), screen_(screen::Blank),
data_screen_(screen::Blank), message_screen_(screen::Blank),
last_render_(0), frame_duration_(2000) {
display_ = new LiquidCrystal_I2C(0x27, 20, 4);
}
Lcd::Lcd(SystemLogger *logger)
: display_cleared_(false), logger_(logger), screen_(screen::Blank),
data_screen_(screen::Blank), message_screen_(screen::Blank),
last_render_(0), frame_duration_(500) {
display_ = new LiquidCrystal_I2C(0x27, 20, 4);
}
Lcd::~Lcd() {
delete display_;
display_ = nullptr;
}
int Lcd::init() {
#ifdef DEEP_DEBUG
if (logger_ != nullptr) {
logger_->deepDebug(String(MOD) + ": init: Begin");
}
#endif
display_->init();
Wire.setClock(400000);
display_->backlight();
this->clear();
display_->setCursor(0, 0);
force_render_ = true;
#ifdef DEEP_DEBUG
if (logger_ != nullptr) {
logger_->deepDebug(String(MOD) + ": init: End");
}
#endif
return 0;
}
int Lcd::printMessage(String message) {
#ifdef DEEP_DEBUG
if (logger_ != nullptr) {
logger_->deepDebug(String(MOD) + ": printMessage: Begin");
}
#endif
String original = message;
this->clear();
if (message.length() > 80) {
message = message.substring(0, 80);
}
String lines[4] = {"", "", "", ""};
int lineIndex = 0;
while (message.length() > 0 && lineIndex < 4) {
if (message.length() <= 20) {
lines[lineIndex++] = message;
break;
}
int splitIndex = message.lastIndexOf(' ', 20);
if (splitIndex == -1 || splitIndex == 0) {
splitIndex = 20;
}
lines[lineIndex++] = message.substring(0, splitIndex);
if (splitIndex < message.length() && message.charAt(splitIndex) == ' ') {
message = message.substring(splitIndex + 1);
} else {
message = message.substring(splitIndex);
}
}
int usedLines = 0;
for (int i = 0; i < 4; i++) {
if (lines[i].length() > 0) {
usedLines++;
}
}
int startRow = 0;
if (usedLines == 1) {
startRow = 1;
} else if (usedLines == 2) {
startRow = 1;
} else {
startRow = 0;
}
int currentRow = startRow;
for (int i = 0; i < 4; i++) {
if (lines[i].length() == 0) {
continue;
}
int col = (20 - lines[i].length()) / 2;
if (col < 0) {
col = 0;
}
display_->setCursor(col, currentRow++);
this->print(lines[i]);
}
#ifdef INFO
if (logger_ != nullptr) {
logger_->info(original);
}
#endif
#ifdef DEEP_DEBUG
if (logger_ != nullptr) {
logger_->deepDebug(String(MOD) + ": printMessage: End");
}
#endif
return 0;
}
int Lcd::loop(unsigned long timeout_ms) {
unsigned long now = millis();
unsigned long start = now;
expireMessageIfNeeded(now);
while (true) {
Task next_task;
bool have_task = false;
if (deferred_task_valid_) {
next_task = deferred_task_;
deferred_task_valid_ = false;
have_task = true;
} else {
if (queue_.pop(next_task) == 0) {
have_task = true;
}
}
if (!have_task) {
break;
}
if (message_active_ && isMessageTask(next_task.type_)) {
deferred_task_ = next_task;
deferred_task_valid_ = true;
break;
}
switch (next_task.type_) {
case task::DisplayGpsDebug:
base_rendered_ = false;
data_screen_ = screen::GpsDebug;
if (!message_active_) {
screen_ = data_screen_;
force_render_ = true;
}
break;
case task::DisplayDriverPrimary:
base_rendered_ = false;
data_screen_ = screen::DriverPrimary;
if (!message_active_) {
screen_ = data_screen_;
force_render_ = true;
}
break;
case task::DisplayMsgGpsFix:
base_rendered_ = false;
activateMessage(screen::MsgGpsFix, next_task.data_);
break;
case task::DisplayMsgTrackDetectOk:
base_rendered_ = false;
activateMessage(screen::MsgTrackDetectOk, next_task.data_);
break;
case task::DisplayMsgConfigNoTracks:
base_rendered_ = false;
activateMessage(screen::MsgConfigNoTracks, next_task.data_);
break;
case task::DisplayMsgBatteryLow:
base_rendered_ = false;
activateMessage(screen::MsgBatteryLow, next_task.data_);
break;
case task::DisplayMsgEngineTempLow:
base_rendered_ = false;
activateMessage(screen::MsgEngineTempLow, next_task.data_);
break;
case task::DisplayMsgEngineTempHigh:
base_rendered_ = false;
activateMessage(screen::MsgEngineTempHigh, next_task.data_);
break;
case task::DisplayMsgLapCounterStart:
base_rendered_ = false;
activateMessage(screen::MsgLapCounterStart, next_task.data_);
break;
case task::DisplayMsgLapCounterLapTime:
base_rendered_ = false;
activateMessage(screen::MsgLapCounterLapTime, next_task.data_);
default:
break;
}
now = millis();
expireMessageIfNeeded(now);
if ((unsigned long)(now - start) >= timeout_ms) {
break;
}
}
now = millis();
expireMessageIfNeeded(now);
screen::LcdScreen active_screen = getActiveScreen();
if (screen_ != active_screen) {
screen_ = active_screen;
force_render_ = true;
}
if (!force_render_ && (unsigned long)(now - last_render_) < frame_duration_) {
return 1;
}
switch (screen_) {
case screen::Blank:
this->clear();
break;
case screen::GpsDebug:
this->renderGpsDebug();
break;
case screen::DriverPrimary:
this->renderDriverPrimary();
break;
case screen::MsgGpsFix:
this->renderMsgGpsFix();
break;
case screen::MsgGpsTrigger:
this->renderMsgGpsTrigger();
break;
case screen::MsgTrackDetectOk:
this->renderMsgTrackDetectOk();
break;
case screen::MsgConfigNoTracks:
this->renderMsgConfigNoTracks();
break;
case screen::MsgBatteryLow:
this->renderMsgBatteryLow();
break;
case screen::MsgEngineTempLow:
this->renderMsgEngineTempLow();
break;
case screen::MsgEngineTempHigh:
this->renderMsgEngineTempHigh();
break;
case screen::MsgLapCounterStart:
this->renderMsgLapCounterStart();
break;
case screen::MsgLapCounterLapTime:
this->renderMsgLapCounterLapTime();
break;
default:
break;
}
last_render_ = now;
force_render_ = false;
return 1;
}
#undef MOD

91
src/modules/lcd/lcd.h Normal file
View File

@@ -0,0 +1,91 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <Arduino.h>
#include <LiquidCrystal_I2C.h>
#include "flags.h"
#include "modules/logger/system_logger.h"
#include "modules/gps/gps.h"
#include "base/task.h"
#include "base/ring_buffer.h"
#include "base/module_base.h"
#include "data/gps_store.h"
#include "data/track_store.h"
#include "data/general_store.h"
namespace screen {
enum LcdScreen : uint8_t {
Blank,
GpsDebug,
DriverPrimary,
MsgGpsFix,
MsgGpsTrigger,
MsgTrackDetectOk,
MsgConfigNoTracks,
MsgBatteryLow,
MsgEngineTempLow,
MsgEngineTempHigh,
MsgLapCounterStart,
MsgLapCounterLapTime,
};
} // namespace screen
class Lcd : public ModuleBase {
private:
LiquidCrystal_I2C *display_;
bool display_cleared_;
SystemLogger *logger_ = nullptr;
screen::LcdScreen screen_;
screen::LcdScreen data_screen_;
screen::LcdScreen message_screen_;
unsigned long last_render_;
unsigned long frame_duration_;
unsigned long message_end_ = 0;
bool message_active_ = false;
bool force_render_ = false;
RingBuffer<Task, 16> queue_;
Task deferred_task_{};
bool deferred_task_valid_ = false;
bool base_rendered_ = false;
void clear();
void print(const String &msg);
void print(char c);
void print(const char c[]);
void print(float d, int digits = 2);
void print(unsigned long l, int base = 10);
void print(long l, int base = 10);
void print(unsigned int i, int base = 10);
void print(int i, int base = 10);
bool isMessageTask(task::Type type);
void activateMessage(screen::LcdScreen msg_screen, unsigned long duration_ms);
void expireMessageIfNeeded(unsigned long now);
screen::LcdScreen getActiveScreen() const;
int renderGpsDebug();
int renderDriverPrimary();
int renderMsgGpsFix();
int renderMsgGpsTrigger();
int renderMsgTrackDetectOk();
int renderMsgConfigNoTracks();
int renderMsgBatteryLow();
int renderMsgEngineTempLow();
int renderMsgEngineTempHigh();
int renderMsgLapCounterStart();
int renderMsgLapCounterLapTime();
public:
int push(const Task &task) override;
Lcd();
Lcd(SystemLogger *logger);
~Lcd();
int init();
int printMessage(String message);
int loop(unsigned long timeout_ms = 500);
};

View File

@@ -0,0 +1,93 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "system_logger.h"
#include "data/general_store.h"
#include <stdio.h>
SystemLogger::SystemLogger(HardwareSerial *output) { output_ = output; }
SystemLogger::~SystemLogger() {}
int SystemLogger::printMessage(String prefix, String message) {
if (output_->availableForWrite()) {
output_->print(millis());
output_->print(prefix);
output_->println(message);
return 0;
}
return 1;
}
#ifdef INFO
int SystemLogger::info(String message) {
return this->printMessage(" [INFO] ", message);
}
int SystemLogger::dumpConfig() {
VehicleConfig config;
configGlobalRead(config);
char buffer[64];
// Auto detect
snprintf(buffer, sizeof(buffer),
"\tAuto detect tracks: %d",
config.auto_detect_track_
);
this->info(String(buffer));
// Track fallback
snprintf(buffer, sizeof(buffer),
"\tTrack fallback: %d",
config.track_fallback_
);
this->info(String(buffer));
this->info("\tVBAT cal factor: " + String(config.vbat_calibration_, 6));
this->info("\tVBAT low: " + String(config.vbat_low_, 2));
this->info("\tTENG low: " + String(config.teng_low_, 2));
this->info("\tTENG high: " + String(config.teng_high_, 2));
// Track slots (one per line)
for (size_t i = 0; i < 8; i++) {
snprintf(buffer, sizeof(buffer),
"\tTrack slot %d: %d",
i + 1,
config.track_slot_occupied_[i]
);
this->info(String(buffer));
}
return 0;
}
#endif
#ifdef WARN
int SystemLogger::warn(String message) {
return this->printMessage(" [WARNING] ", message);
}
#endif
#ifdef ERROR
int SystemLogger::error(String message) {
return this->printMessage(" [ERROR] ", message);
}
#endif
#ifdef DEBUG
int SystemLogger::debug(String message) {
return this->printMessage(" [DEBUG] ", message);
}
#endif
#ifdef DEEP_DEBUG
int SystemLogger::deepDebug(String message) {
return this->printMessage(" [DEEP_DEBUG] ", message);
}
#endif

View File

@@ -0,0 +1,41 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include <Arduino.h>
#include "custom_types.h"
#include "flags.h"
#include "base/ring_buffer.h"
#include "base/task.h"
#include "base/module_base.h"
#include "data/config_store.h"
class SystemLogger {
private:
HardwareSerial *output_;
int printMessage(String prefix, String message);
public:
SystemLogger(HardwareSerial *output);
~SystemLogger();
#ifdef INFO
int info(String message);
int dumpConfig();
#endif
#ifdef WARN
int warn(String message);
#endif
#ifdef ERROR
int error(String message);
#endif
#ifdef DEBUG
int debug(String message);
#endif
#ifdef DEEP_DEBUG
int deepDebug(String message);
#endif
};

View File

@@ -0,0 +1,48 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "telemetry.h"
#include "base/router.h"
#include "data/general_store.h"
int Telemetry::push(const Task &task) { return queue_.push(task); }
Telemetry::Telemetry(HardwareSerial* data_stream) : logger_(nullptr), data_stream_(data_stream) {}
Telemetry::Telemetry(HardwareSerial* data_stream,SystemLogger *logger) : logger_(logger), data_stream_(data_stream) {}
Telemetry::~Telemetry() {}
int Telemetry::init() {
data_stream_->begin(115200);
lora_header_.source_ = 0x01;
lora_header_.dest_ = 0x02;
return 0;
}
int Telemetry::loop() {
unsigned long now = millis();
if (now > last_sent_ + update_interval_) {
TelemetryPacket2 packet;
tengGlobalRead(packet.teng);
vbatGlobalRead(packet.vbat);
GpsData gps;
gpsGlobalRead(gps);
packet.time_stamp = gps.time_;
packet.lat = gps.lat_.value_;
packet.lng = gps.lng_.value_;
packet.speed = gps.speed_.value_;
lora_header_.size_ = sizeof(packet);
lora_header_.crc16_ = crc16_ccitt((uint8_t*)&packet, sizeof(packet));
lora_header_.version_ = 2;
uart_header_.size_ = sizeof(packet) + sizeof(lora_header_);
if (data_stream_->availableForWrite()) {
data_stream_->write((uint8_t*)&uart_header_, sizeof(uart_header_));
data_stream_->write((uint8_t*)&lora_header_, sizeof(lora_header_));
data_stream_->write((uint8_t*)&packet, sizeof(packet));
}
last_sent_ = millis();
}
return 0;
}

View File

@@ -0,0 +1,30 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#include "base/module_base.h"
#include "base/ring_buffer.h"
#include "modules/logger/system_logger.h"
#include "telemetry_common/telemetry_common.h"
#include <Arduino.h>
#include "custom_types.h"
#include "data/gps_store.h"
class Telemetry : public ModuleBase {
private:
SystemLogger *logger_;
RingBuffer<Task, 16> queue_;
HardwareSerial *data_stream_;
unsigned long last_sent_ = 0;
unsigned long update_interval_ = 1000;
TelemetryLoRaHeader lora_header_;
TelemetryUARTHeader uart_header_;
public:
int push(const Task &task) override;
Telemetry(HardwareSerial *data_stream);
Telemetry(HardwareSerial *data_stream, SystemLogger *logger);
~Telemetry();
int init();
int loop();
};

View File

@@ -0,0 +1,70 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "thermocouple.h"
#include "base/router.h"
#include "data/general_store.h"
int Thermocouple::push(const Task &task) { return queue_.push(task); }
Thermocouple::Thermocouple() : logger_(nullptr) {}
Thermocouple::Thermocouple(SystemLogger *logger) : logger_(logger) {}
Thermocouple::~Thermocouple() {}
int Thermocouple::init() {
thermocouple_ = new MAX6675(THERMO_SCK, THERMO_CS, THERMO_SO);
VehicleConfig config;
configGlobalRead(config);
low_ = config.teng_low_;
high_ = config.teng_high_;
return 0;
}
int Thermocouple::loop(unsigned long timeout_ms) {
(void)timeout_ms;
if (millis() > last_read_at_ + update_interval_) {
temperature_ = thermocouple_->readCelsius();
tengGlobalWrite(temperature_);
last_read_at_ = millis();
if (temperature_ > high_) {
if (warning_sent_at_ == 0 ||
millis() > warning_sent_at_ + warning_timeout_) {
router::send(module::Lcd, task::DisplayMsgEngineTempHigh, 2000);
warning_sent_at_ = millis();
}
} else if (temperature_ < low_) {
if (warning_sent_at_ == 0 ||
millis() > warning_sent_at_ + warning_timeout_) {
router::send(module::Lcd, task::DisplayMsgEngineTempLow, 2000);
warning_sent_at_ = millis();
}
}
Task active_task;
int res = queue_.pop(active_task);
if (res == 0) {
if (active_task.target_ == module::Thermocouple) {
} else if (active_task.target_ == module::All) {
switch (active_task.type_) {
case task::AllConfigUpdated: {
VehicleConfig config;
configGlobalRead(config);
low_ = config.teng_low_;
high_ = config.teng_high_;
break;
}
default:
break;
}
};
}
return 0;
}
}

View File

@@ -0,0 +1,35 @@
// Copyright (C) 2026 Hector van der Aa <hector@h3cx.dev>
// Copyright (C) 2026 Association Exergie <association.exergie@gmail.com>
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
#define THERMO_CS A1
#define THERMO_SO A0
#define THERMO_SCK A2
#include "base/module_base.h"
#include "base/ring_buffer.h"
#include "custom_types.h"
#include "modules/logger/system_logger.h"
#include <Arduino.h>
#include <max6675.h>
class Thermocouple : public ModuleBase {
private:
SystemLogger *logger_;
RingBuffer<Task, 16> queue_;
MAX6675 *thermocouple_;
float temperature_;
float low_;
float high_;
unsigned long update_interval_ = 1000;
unsigned long last_read_at_ = 0;
unsigned long warning_sent_at_ = 0;
unsigned long warning_timeout_ = 10000;
public:
int push(const Task &task) override;
Thermocouple();
Thermocouple(SystemLogger *logger);
~Thermocouple();
int init();
int loop(unsigned long timeout_ms = 500);
};

1
src/telemetry_common Symbolic link
View File

@@ -0,0 +1 @@
/home/hector/projects/Exergie/TelemetryCommon/cpp/