25 Commits

Author SHA1 Message Date
12ee18adee added documentation 2025-08-22 17:58:30 +02:00
8393f24ae2 improved WebUI 2025-08-12 14:21:53 +02:00
546e4a1885 fix in JenkinsFIle 2025-06-15 21:41:01 +02:00
2d26a92937 updated jenkins-File 2025-06-15 21:36:52 +02:00
c1513641fc missing default added 2025-06-15 21:31:41 +02:00
a849e65f9a improved build script. 2025-06-15 21:17:55 +02:00
b6f9de2894 some tweaks regarding washMode and Debugger 2025-06-15 21:17:32 +02:00
68d571a747 typo 2025-06-15 14:36:36 +02:00
b7ccffc157 implemented Wash-Mode 2025-06-15 13:23:28 +02:00
c7af5619eb added CLI-Command to reset Tank 2025-06-15 13:22:49 +02:00
3357691a21 centralized LED Control and ModeSwitching in Lubeapp.cpp 2025-06-15 13:22:26 +02:00
5638c03e76 added Stage to build Littlefs 2025-06-02 20:29:13 +02:00
051796b19b edited archiv step in Jenkinsfile 2025-06-02 17:18:20 +02:00
cf032fe516 more Prep for CI 2025-06-02 15:05:42 +02:00
618ee4ce80 updated Libraries 2025-06-02 11:12:17 +02:00
41d38a2afc improved Jenkins File 2025-06-02 10:58:10 +02:00
bb824f0376 clean step in correct order 2025-06-02 10:43:38 +02:00
d08e0cfbb3 Updated JenkinsFIle again 2025-06-02 10:02:09 +02:00
479b1861d1 more bash fixes 2025-06-02 09:55:26 +02:00
b276d74907 fixed JenkinsFIle for sh 2025-06-02 09:49:24 +02:00
8c022188c6 updated Jenkinsfile 2025-06-02 09:38:21 +02:00
4d020b5ced moved JenkinsFile 2025-06-02 09:08:34 +02:00
c399672755 prepare for CI Build 2025-06-02 09:02:28 +02:00
dd34bfe645 massive Update 2025-06-02 09:02:19 +02:00
125fc17c39 PCB revision incremented after tag creation. 2025-05-05 00:16:56 +02:00
31 changed files with 3282 additions and 719 deletions

674
COPYING.GPLv3 Normal file
View File

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

192
DEV.md Normal file
View File

@@ -0,0 +1,192 @@
# Developer Documentation Smart Chain Oiler
Diese Datei richtet sich an Entwickler\:innen, die das Projekt aufbauen, erweitern oder debuggen wollen. Ergänzend zur [README.md](README.md) (Überblick & Features) enthält dieses Dokument Details zu BuildProzess, Debugging, Protokollen und internen Architekturen.
---
## Build & Flash
### PlatformIO Environments
* `pcb_rev_1-2_serial`, `pcb_rev_1-2_ota`
* `pcb_rev_1-3_serial`, `pcb_rev_1-3_ota`
* `pcb_rev_1-4_serial`, `pcb_rev_1-4_ota`
Default: **pcb\_rev\_1-4\_serial**
### Serial Flash
```bash
pio run -e pcb_rev_1-4_serial -t upload
```
### OTA Flash
```bash
pio run -e pcb_rev_1-4_ota -t upload
```
* Port: 8266
* Auth: `ADMIN_PASSWORD` (aus `wifi_credentials.ini`)
### Filesystem Update (LittleFS)
* **Immer zuerst** FSImage flashen, wenn „Benötigte FlashVersion“ ≠ „Installierte“
* `.fs.gz` hochladen → danach `.fw.bin`
---
## Serial Console (115200 Baud)
Der ESP8266 bietet ein einfaches CLI (über UART oder USB). Nützliche Befehle:
| Befehl | Funktion |
| ------------------ | ------------------------------ |
| `help` | Liste aller Kommandos |
| `sysinfo` | Systeminfo (Versionen, Uptime) |
| `netinfo` | Netzwerkinfos (IP, WiFi) |
| `dtc_list` | Aktive DTCs anzeigen |
| `dtc_clear` | DTCListe zurücksetzen |
| `purge` | Entlüften/Pumpimpulse starten |
| `toggle_wifi` | WiFiAP ein/aus |
| `tank_refill` | Tankfüllstand zurücksetzen |
| `isr_debug on/off` | Debug-Ausgabe zu ImpulsISR |
---
## WebSocket API
### Endpoint
`ws://<host>/ws`
### Server → Client Events
* `NOTIFY:<type>;<msg>` → Toast/Alert im UI
* `DEBUG:<text>` → Debugausgabe
* `DTC:<list>` → aktive DTCs (Format: `ts,code,severity,active;…`)
* `MAPPING_STATUS:<map>` → Mapping Keys → Labels (Statuswerte)
* `MAPPING_STATIC:<map>` → Mapping Keys → Labels (Staticwerte)
* `STATUS:<values>` → Livewerte (z. B. Distanzzähler, Tank %)
* `STATIC:<values>` → Konfiguration, Versionen
### Client → Server Events
* Generisches Schema: `btn-<elementId>:<value>`
* Beispiel: `btn-refill:1` (Tankreset), `btn-purge:25` (25 Impulse)
---
## DTC Framework
Severity:
* **INFO** nur Anzeige im WebUI
* **WARN (Orange)** Hinweis, Betrieb läuft weiter
* **CRITICAL (Rot)** Pumpe gestoppt
DTCDefinitionen: siehe [`dtc_defs.txt`](dtc_defs.txt). Im WebUI werden Codes per `dtc_table.json` in Titel & Beschreibung gemappt.
---
## Tankmodell & Persistenz
* `amountPerDose_microL` definiert Ölmenge pro Puls
* Virtueller Tank (ml, Warnschwelle %, Restreichweite)
* Daten persistiert in EEPROM/Flash (Partition PDS)
* Sanity/ChecksumPrüfungen → passende DTCs
---
## Speed Sources
* **Impuls/Pickup:** via Interrupt (konfigurierbar: Puls/Umdrehung, Reifenmaße)
* **GPS (TinyGPSPlus):** Baudrate wählbar, Distanzberechnung
* **CAN (KTMspezifisch):** tested mit KTM 890 Adventure R & 1290 SuperDuke
* **OBD2 CAN/KLine:** in Testphase (PCB ≥ 1.4 für KLine)
---
## LED Control
* Implementiert in `ledcontrol.cpp`
* Farben + Muster (`led_colors.h`)
* BrightnessRange konfigurierbar (WebUI)
* DTC Severity → LED Orange/Rot
---
## Codegen & Versionsverwaltung
* `struct2json.cpp` wird **automatisch generiert** (nicht manuell editieren)
* GitRevision via `codegen/git_rev_macro.py` eingebettet
* FlashVersion Check: „Benötigte vs. Installierte FlashVersion“ (WebUIUpdateTab)
---
## Hardware PinMapping & PCB Revisionen
### PowerPfad (Rev 1.4)
* **+12V Eingang** → **VerpolschutzDiode****StepDown auf 5V** → versorgt **Wemos D1 mini**
* **3,3V** wird vom **Wemos** bereitgestellt (per LDO) und speist Peripherie (CAN, KLine, OLED, EEPROM, WS2812DataLevel ok am D3)
* **Pumpe**: LowSideMOSFET mit **Freilaufdiode** (Entstörung gegen induktive Spannungsspitzen)
### Wemos D1 mini (ESP8266) Pins
| Funktion | BoardPin | GPIO | Bemerkung |
| ---------------------------------- | --------- | ------ | ------------------------------------------------------------------------------------------- |
| **Pumpe (MOSFET, LowSide)** | D0 | GPIO16 | Schaltausgang für Pumpentreiber |
| **I²C SCL (OLED/EEPROM)** | D1 | GPIO5 | U8g2 + I2CEEPROM auf gleichem Bus |
| **I²C SDA (OLED/EEPROM)** | D2 | GPIO4 | PullUps auf 3,3V vorhanden |
| **WS2812 LED Data** | D3 | GPIO0 | Serieller Widerstand im Datenpfad |
| **CockpitTaster** | D4 | GPIO2 | gegen **GND**, Schutzdiode, interner PullUp |
| **SPI SCK (MCP2515)** | D5 | GPIO14 | CANController |
| **SPI MISO (MCP2515)** | D6 | GPIO12 | shared mit internen Leitungen, siehe KLine/UART Hinweis |
| **SPI MOSI (MCP2515)** | D7 | GPIO13 | CANController |
| **CS / CEN / Impuls (per Jumper)** | D8 | GPIO15 | **JumperFunktion**: CS für MCP2515 **oder** **CEN\_KLine** **oder** **ImpulsEingang** |
| **UART0 TX** | TX (J44) | GPIO1 | geht an USBUART **und** an KLineTransceiver (aktiv nur wenn **CEN\_KLine** gesetzt) |
| **UART0 RX / GPSEingang** | RX (J43) | GPIO3 | USBUART **und** GPSEingang; GPSFrames werden vom Parser konsumiert, Rest an CLI geroutet |
> **Hinweis zu KLine:** Der MC33660 wird über **CEN\_KLine** (D8, per LötJumper) nur aktiviert, wenn gesendet/empfangen werden soll. Dadurch bleibt die serielle Konsole (USB) im Normalbetrieb verfügbar.
### CAN / OBDKLine / GPS Anschlüsse
* **CAN:** MCP2515 (SPI) + MCP2551, Signale **CAN\_H**/**CAN\_L** nach außen geführt
* **KLine:** MC33660, UART0 TX/RX zugeschaltet über **CEN\_KLine**
* **GPS (seriell):** UART0 RX an **J4Pin3**, Baudrate im WebUI wählbar; nur RX genutzt
### PCBRevisionen
* **Rev1.2:** Basis (Pumpe, Taster, LED, optional OLED/I²C)
* **Rev1.3:** Verbesserte CANIntegration/PowerPfad
* **Rev1.4:** KLineTransceiver, JumperMux auf **D8** (CS/CEN/Impuls), GPSHeader (J4)
\-------------------|------|-----------------|-------------------------------------------|
\| Taster | D3 | GPIO0 | PullUp, ISRAbfrage |
\| RGBLED (WS2812) | D4 | GPIO2 | Adafruit NeoPixelLib |
\| Pumpe (MOSFET) | D1 | GPIO5 | LowSide Treiber |
\| CANCS | D8 | GPIO15 | MCP2515 CS |
\| CANINT | D0 | GPIO16 | Interrupt vom MCP2515 |
\| OBD2 KLine | D7 | GPIO13 | ab PCB Rev 1.4, Pegelwandler erforderlich |
\| GPS RX | D6 | GPIO12 | Seriell, TinyGPSPlus |
\| OLED I²C SCL | D5 | GPIO14 | U8g2Lib |
\| OLED I²C SDA | D2 | GPIO4 | U8g2Lib |
> Hinweis: tatsächliches Mapping je nach `config.h` und PCBRevision. Tabelle zeigt Standardzuordnung Rev1.4.
### PCB Revisionen
* **Rev 1.2:** Basisfunktionen, kein OBD2Support
* **Rev 1.3:** Verbesserte CANIntegration, stabileres PowerDesign
* **Rev 1.4:** zusätzlicher Pegelwandler für **OBD2 KLine**, vorbereitet für GPSModul
---
## Known Limitations / TODO
* OBD2 CAN/KLine: nur Basisfunktionen, erweiterte PIDUnterstützung offen
* GPS: bei schlechtem Empfang kann DTC „NO GPS SIGNAL“ spammen
* OLED: nur BasicStatusanzeigen; keine volle UI
---

245
Documentation/Manual.md Normal file
View File

@@ -0,0 +1,245 @@
# Kettenöler Bedienungsanleitung
Diese Anleitung beschreibt Installation, Bedienung und Wartung des Smart Chain Oiler Systems.
---
## 1. Einleitung & Sicherheit
Der Smart Chain Oiler ist ein intelligenter, mikrocontrollergesteuerter Kettenöler für Motorräder.
⚠️ **Sicherheits- und Nutzungshinweise:**
* Der Einbau erfordert grundlegende Kenntnisse in Elektronik und Fahrzeugtechnik.
* Öl darf nur auf die Kette aufgetragen werden nicht auf Reifen oder Bremsen.
* Ein leerer Tank oder Fehlfunktion kann zum Ausfall der automatischen Schmierung führen. Kette regelmäßig prüfen.
* Nutzung auf eigene Verantwortung.
---
## 2. Systemübersicht
**Bedienung:**
* 1x Taster (multifunktional)
* RGBLED (Statusanzeige)
* Optional: I²C OLEDDisplay (128x64)
* Erweiterte Einstellungen und Wartung über WebUI (WiFiAccess Point)
**Komponenten:**
* ESP8266 MCU (Wemos D1 mini)
* Pumpe (empfohlen: McCoi SpezialÖlpumpe)
* Tank (frei wählbar, Größe im WebUI einstellbar)
---
## 3. Installation & Anschluss
### Versorgung
* **Spannungsversorgung:** 12 V DC
* **Anschluss:** **Zündungs-Plus (ACC)**, nicht Dauerplus (verhindert Batterieentladung)
* **Absicherung:** **5 A Sicherung** empfohlen (kurzzeitige hohe Stromaufnahme von 1A bis 2A der Pumpe möglich)
### Anschlussklemmen & Header
* **Power-Klemme (3-polige Schraubklemme):**
* Pin 1: **+12 V** (Zündungsplus, ggf. Sicherung vorschalten)
* Pin 2: **Pumpen-Minus** (geht auf MOSFET → wird geschaltet)
* Pin 3: **GND** (gemeinsame Masse)
* 👉 Pumpen-Plus kommt direkt an +12 V (hinter der Sicherung).
* **Cockpit-Header (LED/Taster/OLED):**
| Pin | Signal | Bemerkung |
| --- | --------- | ----------------------------------------------------------- |
| 1 | SDA (I²C) | Datenleitung für OLED, Pull-Up 4k7 auf 3,3 V |
| 2 | +5 V | Versorgung für Cockpit (LED, OLED etc.) |
| 3 | SCL (I²C) | Taktleitung für OLED, Pull-Up 4k7 auf 3,3 V |
| 4 | LED Data | WS2812 LED Datenleitung (über R3=100 Ω) |
| 5 | +3,3 V | I²C/OLED Versorgung (vom ESP8266 intern bereitgestellt) |
| 6 | Taster | GPIO2, gegen GND, mit Schutzdiode |
| 7 | GND | Masse |
| 8 | GND | Masse |
* ⚠️ Die Leitungen des Display sollten **kurz gehalten werden** (Faustregel: <20 cm bei ungeschirmten Leitungen).
* **Signal-Header (Eingänge):**
| Pin | Signal | Bemerkung |
| --- | ----------- | -------------------------------------------------------- |
| 1 | GND | Masse |
| 2 | K-Line OBD2 | OBD2 K-Line, geht auf den MC33660 |
| 3 | SERIAL\_RX | UART0 RX (für GPS oder CLI), geschützt durch Diode |
| 4 | SERIAL\_TX | UART0 TX (CLI, Debug) |
| 5 | GPIO\_PULSE | Impulseingang (Pickup/Tachosignal), RC-gefiltert + Diode |
| 6 | CAN\_L | Low-Leitung für CAN |
| 7 | GND | Masse (zweiter Anschluss, symmetrisch) |
| 8 | CAN\_H | High-Leitung für CAN |
👉 Details siehe AnschlussSchemata der jeweiligen PCBRevision.
---
## 4. LED-Anzeigen
* **Grün** Normalmodus (Standard-Schmierung)
* **Blau** Regenmodus (verstärkte Schmierung)
* **Pink blinkend** Prime/Entlüften aktiv
* **Türkis** WashMode aktiv
* **Gelb aufblitzend** WiFiAP aktiv
* **Orange** Warnung (Tank niedrig, EEPROM Sanity, oder anderes DTC/WARN)
* **Rot** Kritischer Fehler (DTC\_CRITICAL, Öler gestoppt)
---
## 5. Bedienung über den Taster
Prinzip: **Taste gedrückt halten → LEDFarbe beobachten → bei gewünschter Farbe loslassen**.
* **0,53,5 s halten loslassen:** Normal (Grün) Regen (Blau)
* **3,56,5 s halten loslassen:** WashMode aktivieren (Türkis)
* **6,59,5 s halten loslassen:** Prime / Entlüften starten (Pink blinkend)
* **9,512,5 s halten loslassen:** WiFiAP ein-/ausschalten (Gelb)
---
## 6. Funktionsbeschreibung der Modi
### Normalmodus (Grün)
* Schmierimpuls alle **8.000 m** (Standard, im WebUI anpassbar)
* Zähler metergenau, auch über Neustarts hinweg
### Regenmodus (Blau)
* Schmierimpuls alle **4.000 m** (Standard, im WebUI anpassbar)
* Zuletzt gewählter Modus wird gespeichert und nach Neustart übernommen
### WashMode (Türkis)
* Für Pflege nach Reinigung (z. B. Hochdruckreiniger)
* Standard: alle **10 m** ein Impuls über **500 m**
* Danach automatische Rückkehr in Normal/Regen
### Prime / Entlüften (Pink blinkend)
* Standard: **25 Impulse**, Leitung spülen oder Luft entfernen
* Auch über WebUI startbar
### WiFi-AP (Gelb)
* Aktiviert den Access Point für das WebUI
* Zugriff auf Einstellungen, Wartung und Updates
**So gehts:**
1. **Taster gedrückt halten**, bis die LED **Gelb** aufleuchtet dann loslassen.
2. Der WiFi-Hotspot startet und bleibt **bis zum nächsten Neustart** aktiv.
3. SSID: **`ChainLube_XXXXXX`** (XXXXXX = ChipID des ESP8266)
4. Passwort: **`wifiappass`**
5. Smartphone/PC mit dem Hotspot verbinden.
* Android meldet evtl. *„Dieses Netzwerk hat keine Internetverbindung“* trotzdem verbunden bleiben.
6. Browser öffnen **[http://10.0.0.1](http://10.0.0.1)** aufrufen WebUI erscheint.
### Tanküberwachung
* Virtuell, basierend auf Tankgröße im WebUI
* **Orange LED + WARN DTC:** Tank fast leer
* **Rot LED + CRITICAL DTC:** Tank leer, Öler gestoppt
* Tank jederzeit im WebUI zurücksetzbar
---
## 7. WebUI Bedienung
WiFiAP öffnen Browser `10.0.0.1`
### Tabs & Funktionen
* **Home:** Tankstand %, Status, aktive DTCs
* **Wartung:** Tank zurücksetzen, Purge starten, Einmessen, LiveDebug, Reboot
* **Einstellungen:** Signalquelle (Impuls/CAN/GPS/OBD), Dosierung, Tankgröße, LED, WiFi
* **Update:** Firmwareversionen, FlashVersion, GitRevision, Firmware und FilesystemUpdate, EEPROMBackup/Restore
👉 Wechsel der Signalquelle führt zu Neustart!
---
Genau so machen wirs 🐺✨ hier meine überarbeiteten Versionen für die beiden Abschnitte plus ein Vorschlag für den Feedback-Teil am Ende:
---
### **8. Diagnose (DTC)**
### Kategorien
* **INFO:** Nur im WebUI sichtbar, keine LED-Reaktion
* **WARN (Orange):** Hinweis, Betrieb läuft weiter
* **CRITICAL (Rot):** Kritisch, Pumpe gestoppt
### Darstellung
* **Alle aktiven DTCs** werden **im WebUI mit Volltext und Beschreibung angezeigt**.
* Über die LED wird nur die Schwere (Warnung/Kritisch) signalisiert.
### Typische Beispiele
* **Tank leer (CRITICAL, Rot):** Vorrat nachfüllen, Tank im WebUI zurücksetzen
* **Tank niedrig (WARN, Orange):** Vorrat bald auffüllen
* **EEPROM/Flash Fehler (CRITICAL, Rot):** Speicher zurücksetzen, ggf. Hardware prüfen
* **GPS/CAN/OBD Fehler:** Verbindung oder Konfiguration prüfen
* **Dummy-DTCs:** nur für Debugzwecke
👉 Vollständige Liste aller Codes und Texte siehe `dtc_defs.txt` / `dtc_table.json`.
---
## 9. Troubleshooting
| Symptom | Ursache | Lösung |
| -------------------------- | ------------------------------------------ | --------------------------------------------- |
| LED dauerhaft Rot | Kritischer DTC (Tank leer, EEPROM, Flash) | WebUI öffnen, DTC prüfen, Ursache beheben |
| Keine Schmierung | Tank leer oder Pumpe blockiert | Tank auffüllen, Purge starten, Pumpe prüfen |
| Kein WebUI erreichbar | AP nicht aktiv | Taste 9,512,5 s halten, auf Gelb warten |
| GPS zeigt nichts | Falsche Baudrate oder kein Signal | Baudrate im WebUI prüfen, Antenne freie Sicht |
| CAN/OBD funktioniert nicht | Falsches Modell oder Jumper falsch gesetzt | Einstellungen prüfen, Jumper korrekt setzen |
---
---
### **10. Wartung**
* Regelmäßig Ölstand prüfen und im WebUI nach dem Nachfüllen **Tank zurücksetzen**
* Nach längeren Standzeiten (z. B. Winterpause) einmal **Prime/Purge** laufen lassen, um die Leitung zu spülen
* Kabel & Anschlüsse auf festen Sitz und Isolation prüfen
* Software- und WebUI-Updates **nur bei Bedarf** einspielen (z. B. bei neuen Funktionen oder Bugfixes)
---
## **11. Technische Daten**
* **Versorgung:** 12 V DC (Motorradbatterie), \~50 mA (ohne Pumpe)
* **MCU:** ESP8266 (Wemos D1 mini)
* **Tankgröße:** frei einstellbar (ml)
* **Dosierung:** konfigurierbar in µl pro Puls
* **Signalquellen:** Impuls, GPS, CAN (KTM), OBD2 (CAN/KLine)
* **Speicher:** EEPROM für CFG & PDS, Checksummen & Sanity Checks
* **Pumpen:** abgestimmt auf McCoi SpezialÖlpumpe
* **Betriebstemperatur:** 10 bis +70 °C
---
## **12. Feedback & Community**
Dieses Projekt lebt vom Feedback und den Ideen der Nutzer.
* Wenn du Fehler findest oder Verbesserungsvorschläge hast melde dich!
* Auch neue Ideen für Features oder Anpassungen an andere Motorräder sind willkommen.
* Rückmeldungen helfen, den Öler stabiler, praktischer und vielseitiger zu machen.
* Diskussionen, Tests und Spinnereien sind ausdrücklich erwünscht manchmal entstehen daraus die besten Features.
💡 Ja, mir ist klar: das Ding ist für einfach nur Kette ölen eigentlich hoffnungslos **over-engineered** aber genau das macht den Reiz aus. Ich hab Spaß daran und freue mich über alles, was das Projekt noch ein Stück nerdiger, smarter oder einfach nützlicher macht.

View File

@@ -11738,7 +11738,7 @@
(layer "Edge.Cuts")
(uuid "da6f4122-0ecc-496f-b0fd-e4abef534976")
)
(gr_text "KTM CAN ChainLube Mk1\nPCB Rev.: 1.4\n(c) 2025 - Marcel Peterkau"
(gr_text "KTM CAN ChainLube Mk1\nPCB Rev.: 1.5\n(c) 2025 - Marcel Peterkau"
(at 156.464 85.344 90)
(layer "B.SilkS")
(uuid "00000000-0000-0000-0000-000061de6936")

115
Jenkinsfile vendored Normal file
View File

@@ -0,0 +1,115 @@
pipeline {
agent any
environment {
PIO_HOME_DIR = "${WORKSPACE}/.pio"
VENV_PATH = "${WORKSPACE}/Software/.venv"
}
stages {
stage('🧰 Setup PlatformIO') {
steps {
dir('Software') {
sh """
[ -d .venv ] || python3 -m venv .venv
${env.VENV_PATH}/bin/pip install --upgrade pip platformio
"""
}
}
}
stage('📄 Dummy WiFi-Creds') {
steps {
dir('Software') {
writeFile file: 'wifi_credentials.ini', text: '''
[wifi_cred]
wifi_ssid_client = DummySSID
wifi_password_client = DummyPass
admin_password = Admin123
wifi_ap_password = DummyAP
'''.stripIndent()
}
}
}
stage('🧱 Build Firmware for All Environments') {
steps {
dir('Software') {
script {
def allEnvironments = ['pcb_rev_1-2_serial', 'pcb_rev_1-3_serial', 'pcb_rev_1-4_serial']
for (envName in allEnvironments) {
echo "🔧 Baue Firmware für: ${envName}"
sh "${env.VENV_PATH}/bin/platformio run -e ${envName}"
}
env.REPRESENTATIVE_ENV = allEnvironments[0]
}
}
}
}
stage('📁 Build Filesystem') {
steps {
dir('Software') {
script {
echo "📁 Baue Filesystem für ${env.REPRESENTATIVE_ENV} (repräsentativ)"
sh "${env.VENV_PATH}/bin/platformio run -t buildfs -e ${env.REPRESENTATIVE_ENV}"
}
}
}
}
stage('📦 Find & Archive Firmware') {
steps {
dir('Software') {
script {
echo "🔍 Suche nach Firmware (.fw.bin) und Filesystem (.fs.gz) Artefakten..."
def firmwareFiles = findFiles(glob: '.pio/build/**/*.fw.bin')
def fsFiles = findFiles(glob: '.pio/build/**/*.fs.gz')
if (firmwareFiles.length == 0 && fsFiles.length == 0) {
echo "⚠️ Keine passenden Artefakte (.fw.bin / .fs.gz) gefunden nichts zu archivieren."
} else {
firmwareFiles.each { echo "📦 Firmware: ${it.path}" }
fsFiles.each { echo "📦 Filesystem: ${it.path}" }
def allArtifacts = (firmwareFiles + fsFiles).collect { it.path }
archiveArtifacts artifacts: allArtifacts.join(', ')
}
}
}
}
}
stage('🔌 Flash Hardware (Dummy)') {
steps {
echo "TODO: Flash-Script aufrufen, z.B.: python3 Hardware/flash.py /dev/ttyUSB0"
}
}
stage('🧠 Run Tests (Dummy)') {
steps {
dir('Testing') {
echo "TODO: Testing mit z.B.: python3 test_runner.py oder pytest starten"
}
}
}
stage('🧹 Cleanup Build Output') {
steps {
dir('Software') {
sh "rm -rf .pio"
}
}
}
}
post {
success {
echo "✅ CI abgeschlossen Firmware gebaut, Dummy-Stages bereit"
}
failure {
echo "❌ Fehler im Build Logs checken, Commander Seraphon"
}
}
}

438
LICENSE.CC-BY-NC-SA-4.0 Normal file
View File

@@ -0,0 +1,438 @@
Attribution-NonCommercial-ShareAlike 4.0 International
=======================================================================
Creative Commons Corporation ("Creative Commons") is not a law firm and
does not provide legal services or legal advice. Distribution of
Creative Commons public licenses does not create a lawyer-client or
other relationship. Creative Commons makes its licenses and related
information available on an "as-is" basis. Creative Commons gives no
warranties regarding its licenses, any material licensed under their
terms and conditions, or any related information. Creative Commons
disclaims all liability for damages resulting from their use to the
fullest extent possible.
Using Creative Commons Public Licenses
Creative Commons public licenses provide a standard set of terms and
conditions that creators and other rights holders may use to share
original works of authorship and other material subject to copyright
and certain other rights specified in the public license below. The
following considerations are for informational purposes only, are not
exhaustive, and do not form part of our licenses.
Considerations for licensors: Our public licenses are
intended for use by those authorized to give the public
permission to use material in ways otherwise restricted by
copyright and certain other rights. Our licenses are
irrevocable. Licensors should read and understand the terms
and conditions of the license they choose before applying it.
Licensors should also secure all rights necessary before
applying our licenses so that the public can reuse the
material as expected. Licensors should clearly mark any
material not subject to the license. This includes other CC-
licensed material, or material used under an exception or
limitation to copyright. More considerations for licensors:
wiki.creativecommons.org/Considerations_for_licensors
Considerations for the public: By using one of our public
licenses, a licensor grants the public permission to use the
licensed material under specified terms and conditions. If
the licensor's permission is not necessary for any reason--for
example, because of any applicable exception or limitation to
copyright--then that use is not regulated by the license. Our
licenses grant only permissions under copyright and certain
other rights that a licensor has authority to grant. Use of
the licensed material may still be restricted for other
reasons, including because others have copyright or other
rights in the material. A licensor may make special requests,
such as asking that all changes be marked or described.
Although not required by our licenses, you are encouraged to
respect those requests where reasonable. More considerations
for the public:
wiki.creativecommons.org/Considerations_for_licensees
=======================================================================
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
Public License
By exercising the Licensed Rights (defined below), You accept and agree
to be bound by the terms and conditions of this Creative Commons
Attribution-NonCommercial-ShareAlike 4.0 International Public License
("Public License"). To the extent this Public License may be
interpreted as a contract, You are granted the Licensed Rights in
consideration of Your acceptance of these terms and conditions, and the
Licensor grants You such rights in consideration of benefits the
Licensor receives from making the Licensed Material available under
these terms and conditions.
Section 1 -- Definitions.
a. Adapted Material means material subject to Copyright and Similar
Rights that is derived from or based upon the Licensed Material
and in which the Licensed Material is translated, altered,
arranged, transformed, or otherwise modified in a manner requiring
permission under the Copyright and Similar Rights held by the
Licensor. For purposes of this Public License, where the Licensed
Material is a musical work, performance, or sound recording,
Adapted Material is always produced where the Licensed Material is
synched in timed relation with a moving image.
b. Adapter's License means the license You apply to Your Copyright
and Similar Rights in Your contributions to Adapted Material in
accordance with the terms and conditions of this Public License.
c. BY-NC-SA Compatible License means a license listed at
creativecommons.org/compatiblelicenses, approved by Creative
Commons as essentially the equivalent of this Public License.
d. Copyright and Similar Rights means copyright and/or similar rights
closely related to copyright including, without limitation,
performance, broadcast, sound recording, and Sui Generis Database
Rights, without regard to how the rights are labeled or
categorized. For purposes of this Public License, the rights
specified in Section 2(b)(1)-(2) are not Copyright and Similar
Rights.
e. Effective Technological Measures means those measures that, in the
absence of proper authority, may not be circumvented under laws
fulfilling obligations under Article 11 of the WIPO Copyright
Treaty adopted on December 20, 1996, and/or similar international
agreements.
f. Exceptions and Limitations means fair use, fair dealing, and/or
any other exception or limitation to Copyright and Similar Rights
that applies to Your use of the Licensed Material.
g. License Elements means the license attributes listed in the name
of a Creative Commons Public License. The License Elements of this
Public License are Attribution, NonCommercial, and ShareAlike.
h. Licensed Material means the artistic or literary work, database,
or other material to which the Licensor applied this Public
License.
i. Licensed Rights means the rights granted to You subject to the
terms and conditions of this Public License, which are limited to
all Copyright and Similar Rights that apply to Your use of the
Licensed Material and that the Licensor has authority to license.
j. Licensor means the individual(s) or entity(ies) granting rights
under this Public License.
k. NonCommercial means not primarily intended for or directed towards
commercial advantage or monetary compensation. For purposes of
this Public License, the exchange of the Licensed Material for
other material subject to Copyright and Similar Rights by digital
file-sharing or similar means is NonCommercial provided there is
no payment of monetary compensation in connection with the
exchange.
l. Share means to provide material to the public by any means or
process that requires permission under the Licensed Rights, such
as reproduction, public display, public performance, distribution,
dissemination, communication, or importation, and to make material
available to the public including in ways that members of the
public may access the material from a place and at a time
individually chosen by them.
m. Sui Generis Database Rights means rights other than copyright
resulting from Directive 96/9/EC of the European Parliament and of
the Council of 11 March 1996 on the legal protection of databases,
as amended and/or succeeded, as well as other essentially
equivalent rights anywhere in the world.
n. You means the individual or entity exercising the Licensed Rights
under this Public License. Your has a corresponding meaning.
Section 2 -- Scope.
a. License grant.
1. Subject to the terms and conditions of this Public License,
the Licensor hereby grants You a worldwide, royalty-free,
non-sublicensable, non-exclusive, irrevocable license to
exercise the Licensed Rights in the Licensed Material to:
a. reproduce and Share the Licensed Material, in whole or
in part, for NonCommercial purposes only; and
b. produce, reproduce, and Share Adapted Material for
NonCommercial purposes only.
2. Exceptions and Limitations. For the avoidance of doubt, where
Exceptions and Limitations apply to Your use, this Public
License does not apply, and You do not need to comply with
its terms and conditions.
3. Term. The term of this Public License is specified in Section
6(a).
4. Media and formats; technical modifications allowed. The
Licensor authorizes You to exercise the Licensed Rights in
all media and formats whether now known or hereafter created,
and to make technical modifications necessary to do so. The
Licensor waives and/or agrees not to assert any right or
authority to forbid You from making technical modifications
necessary to exercise the Licensed Rights, including
technical modifications necessary to circumvent Effective
Technological Measures. For purposes of this Public License,
simply making modifications authorized by this Section 2(a)
(4) never produces Adapted Material.
5. Downstream recipients.
a. Offer from the Licensor -- Licensed Material. Every
recipient of the Licensed Material automatically
receives an offer from the Licensor to exercise the
Licensed Rights under the terms and conditions of this
Public License.
b. Additional offer from the Licensor -- Adapted Material.
Every recipient of Adapted Material from You
automatically receives an offer from the Licensor to
exercise the Licensed Rights in the Adapted Material
under the conditions of the Adapter's License You apply.
c. No downstream restrictions. You may not offer or impose
any additional or different terms or conditions on, or
apply any Effective Technological Measures to, the
Licensed Material if doing so restricts exercise of the
Licensed Rights by any recipient of the Licensed
Material.
6. No endorsement. Nothing in this Public License constitutes or
may be construed as permission to assert or imply that You
are, or that Your use of the Licensed Material is, connected
with, or sponsored, endorsed, or granted official status by,
the Licensor or others designated to receive attribution as
provided in Section 3(a)(1)(A)(i).
b. Other rights.
1. Moral rights, such as the right of integrity, are not
licensed under this Public License, nor are publicity,
privacy, and/or other similar personality rights; however, to
the extent possible, the Licensor waives and/or agrees not to
assert any such rights held by the Licensor to the limited
extent necessary to allow You to exercise the Licensed
Rights, but not otherwise.
2. Patent and trademark rights are not licensed under this
Public License.
3. To the extent possible, the Licensor waives any right to
collect royalties from You for the exercise of the Licensed
Rights, whether directly or through a collecting society
under any voluntary or waivable statutory or compulsory
licensing scheme. In all other cases the Licensor expressly
reserves any right to collect such royalties, including when
the Licensed Material is used other than for NonCommercial
purposes.
Section 3 -- License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the
following conditions.
a. Attribution.
1. If You Share the Licensed Material (including in modified
form), You must:
a. retain the following if it is supplied by the Licensor
with the Licensed Material:
i. identification of the creator(s) of the Licensed
Material and any others designated to receive
attribution, in any reasonable manner requested by
the Licensor (including by pseudonym if
designated);
ii. a copyright notice;
iii. a notice that refers to this Public License;
iv. a notice that refers to the disclaimer of
warranties;
v. a URI or hyperlink to the Licensed Material to the
extent reasonably practicable;
b. indicate if You modified the Licensed Material and
retain an indication of any previous modifications; and
c. indicate the Licensed Material is licensed under this
Public License, and include the text of, or the URI or
hyperlink to, this Public License.
2. You may satisfy the conditions in Section 3(a)(1) in any
reasonable manner based on the medium, means, and context in
which You Share the Licensed Material. For example, it may be
reasonable to satisfy the conditions by providing a URI or
hyperlink to a resource that includes the required
information.
3. If requested by the Licensor, You must remove any of the
information required by Section 3(a)(1)(A) to the extent
reasonably practicable.
b. ShareAlike.
In addition to the conditions in Section 3(a), if You Share
Adapted Material You produce, the following conditions also apply.
1. The Adapter's License You apply must be a Creative Commons
license with the same License Elements, this version or
later, or a BY-NC-SA Compatible License.
2. You must include the text of, or the URI or hyperlink to, the
Adapter's License You apply. You may satisfy this condition
in any reasonable manner based on the medium, means, and
context in which You Share Adapted Material.
3. You may not offer or impose any additional or different terms
or conditions on, or apply any Effective Technological
Measures to, Adapted Material that restrict exercise of the
rights granted under the Adapter's License You apply.
Section 4 -- Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that
apply to Your use of the Licensed Material:
a. for the avoidance of doubt, Section 2(a)(1) grants You the right
to extract, reuse, reproduce, and Share all or a substantial
portion of the contents of the database for NonCommercial purposes
only;
b. if You include all or a substantial portion of the database
contents in a database in which You have Sui Generis Database
Rights, then the database in which You have Sui Generis Database
Rights (but not its individual contents) is Adapted Material,
including for purposes of Section 3(b); and
c. You must comply with the conditions in Section 3(a) if You Share
all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not
replace Your obligations under this Public License where the Licensed
Rights include other Copyright and Similar Rights.
Section 5 -- Disclaimer of Warranties and Limitation of Liability.
a. UNLESS OTHERWISE SEPARATELY UNDERTAKEN BY THE LICENSOR, TO THE
EXTENT POSSIBLE, THE LICENSOR OFFERS THE LICENSED MATERIAL AS-IS
AND AS-AVAILABLE, AND MAKES NO REPRESENTATIONS OR WARRANTIES OF
ANY KIND CONCERNING THE LICENSED MATERIAL, WHETHER EXPRESS,
IMPLIED, STATUTORY, OR OTHER. THIS INCLUDES, WITHOUT LIMITATION,
WARRANTIES OF TITLE, MERCHANTABILITY, FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, ABSENCE OF LATENT OR OTHER DEFECTS,
ACCURACY, OR THE PRESENCE OR ABSENCE OF ERRORS, WHETHER OR NOT
KNOWN OR DISCOVERABLE. WHERE DISCLAIMERS OF WARRANTIES ARE NOT
ALLOWED IN FULL OR IN PART, THIS DISCLAIMER MAY NOT APPLY TO YOU.
b. TO THE EXTENT POSSIBLE, IN NO EVENT WILL THE LICENSOR BE LIABLE
TO YOU ON ANY LEGAL THEORY (INCLUDING, WITHOUT LIMITATION,
NEGLIGENCE) OR OTHERWISE FOR ANY DIRECT, SPECIAL, INDIRECT,
INCIDENTAL, CONSEQUENTIAL, PUNITIVE, EXEMPLARY, OR OTHER LOSSES,
COSTS, EXPENSES, OR DAMAGES ARISING OUT OF THIS PUBLIC LICENSE OR
USE OF THE LICENSED MATERIAL, EVEN IF THE LICENSOR HAS BEEN
ADVISED OF THE POSSIBILITY OF SUCH LOSSES, COSTS, EXPENSES, OR
DAMAGES. WHERE A LIMITATION OF LIABILITY IS NOT ALLOWED IN FULL OR
IN PART, THIS LIMITATION MAY NOT APPLY TO YOU.
c. The disclaimer of warranties and limitation of liability provided
above shall be interpreted in a manner that, to the extent
possible, most closely approximates an absolute disclaimer and
waiver of all liability.
Section 6 -- Term and Termination.
a. This Public License applies for the term of the Copyright and
Similar Rights licensed here. However, if You fail to comply with
this Public License, then Your rights under this Public License
terminate automatically.
b. Where Your right to use the Licensed Material has terminated under
Section 6(a), it reinstates:
1. automatically as of the date the violation is cured, provided
it is cured within 30 days of Your discovery of the
violation; or
2. upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any
right the Licensor may have to seek remedies for Your violations
of this Public License.
c. For the avoidance of doubt, the Licensor may also offer the
Licensed Material under separate terms or conditions or stop
distributing the Licensed Material at any time; however, doing so
will not terminate this Public License.
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public
License.
Section 7 -- Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different
terms or conditions communicated by You unless expressly agreed.
b. Any arrangements, understandings, or agreements regarding the
Licensed Material not stated herein are separate from and
independent of the terms and conditions of this Public License.
Section 8 -- Interpretation.
a. For the avoidance of doubt, this Public License does not, and
shall not be interpreted to, reduce, limit, restrict, or impose
conditions on any use of the Licensed Material that could lawfully
be made without permission under this Public License.
b. To the extent possible, if any provision of this Public License is
deemed unenforceable, it shall be automatically reformed to the
minimum extent necessary to make it enforceable. If the provision
cannot be reformed, it shall be severed from this Public License
without affecting the enforceability of the remaining terms and
conditions.
c. No term or condition of this Public License will be waived and no
failure to comply consented to unless expressly agreed to by the
Licensor.
d. Nothing in this Public License constitutes or may be interpreted
as a limitation upon, or waiver of, any privileges and immunities
that apply to the Licensor or You, including from the legal
processes of any jurisdiction or authority.
=======================================================================
Creative Commons is not a party to its public
licenses. Notwithstanding, Creative Commons may elect to apply one of
its public licenses to material it publishes and in those instances
will be considered the “Licensor.” The text of the Creative Commons
public licenses is dedicated to the public domain under the CC0 Public
Domain Dedication. Except for the limited purpose of indicating that
material is shared under a Creative Commons public license or as
otherwise permitted by the Creative Commons policies published at
creativecommons.org/policies, Creative Commons does not authorize the
use of the trademark "Creative Commons" or any other trademark or logo
of Creative Commons without its prior written consent including,
without limitation, in connection with any unauthorized modifications
to any of its public licenses or any other arrangements,
understandings, or agreements concerning use of licensed material. For
the avoidance of doubt, this paragraph does not form part of the
public licenses.
Creative Commons may be contacted at creativecommons.org.

67
LICENSE.CERN-OHL-S-2.0 Normal file
View File

@@ -0,0 +1,67 @@
CERN Open Hardware Licence Version 2 - Strongly Reciprocal
Preamble
CERN has developed this licence to promote collaboration among hardware designers and to provide a legal tool which supports the freedom to use, study, modify, share and distribute hardware designs and products based on those designs. Version 2 of the CERN Open Hardware Licence comes in three variants: CERN-OHL-P (permissive); and two reciprocal licences: CERN-OHL-W (weakly reciprocal) and this licence, CERN-OHL-S (strongly reciprocal).
The CERN-OHL-S is copyright CERN 2020. Anyone is welcome to use it, in unmodified form only.
Use of this Licence does not imply any endorsement by CERN of any Licensor or their designs nor does it imply any involvement by CERN in their development.
1 Definitions
1.1 'Licence' means this CERN-OHL-S.
1.2 'Compatible Licence' means
a) any earlier version of the CERN Open Hardware licence, or
b) any version of the CERN-OHL-S, or
c) any licence which permits You to treat the Source to which it applies as licensed under CERN-OHL-S provided that on Conveyance of any such Source, or any associated Product You treat the Source in question as being licensed under CERN-OHL-S.
1.3 'Source' means information such as design materials or digital code which can be applied to Make or test a Product or to prepare a Product for use, Conveyance or sale, regardless of its medium or how it is expressed. It may include Notices.
1.4 'Covered Source' means Source that is explicitly made available under this Licence.
1.5 'Product' means any device, component, work or physical object, whether in finished or intermediate form, arising from the use, application or processing of Covered Source.
1.6 'Make' means to create or configure something, whether by manufacture, assembly, compiling, loading or applying Covered Source or another Product or otherwise.
1.7 'Available Component' means any part, sub-assembly, library or code which:
a) is licensed to You as Complete Source under a Compatible Licence; or
b) is available, at the time a Product or the Source containing it is first Conveyed, to You and any other prospective licensees
i) as a physical part with sufficient rights and information (including any configuration and programming files and information about its characteristics and interfaces) to enable it either to be Made itself, or to be sourced and used to Make the Product; or
ii) as part of the normal distribution of a tool used to design or Make the Product.
1.8 'Complete Source' means the set of all Source necessary to Make a Product, in the preferred form for making modifications, including necessary installation and interfacing information both for the Product, and for any included Available Components. If the format is proprietary, it must also be made available in a format (if the proprietary tool can create it) which is viewable with a tool available to potential licensees and licensed under a licence approved by the Free Software Foundation or the Open Source Initiative. Complete Source need not include the Source of any Available Component, provided that You include in the Complete Source sufficient information to enable a recipient to Make or source and use the Available Component to Make the Product.
1.9 'Source Location' means a location where a Licensor has placed Covered Source, and which that Licensor reasonably believes will remain easily accessible for at least three years for anyone to obtain a digital copy.
1.10 'Notice' means copyright, acknowledgement and trademark notices, Source Location references, modification notices (subsection 3.3(b)) and all notices that refer to this Licence and to the disclaimer of warranties that are included in the Covered Source.
1.11 'Licensee' or 'You' means any person exercising rights under this Licence.
1.12 'Licensor' means a natural or legal person who creates or modifies Covered Source. A person may be a Licensee and a Licensor at the same time.
1.13 'Convey' means to communicate to the public or distribute.
2 Applicability
2.1 This Licence governs the use, copying, modification, Conveying of Covered Source and Products, and the Making of Products. By exercising any right granted under this Licence, You irrevocably accept these terms and conditions.
2.2 This Licence is granted by the Licensor directly to You, and shall apply worldwide and without limitation in time.
2.3 You shall not attempt to restrict by contract or otherwise the rights granted under this Licence to other Licensees.
2.4 This Licence is not intended to restrict fair use, fair dealing, or any other similar right.
3 Copying, modifying and Conveying Covered Source
3.1 You may copy and Convey verbatim copies of Covered Source, in any medium, provided You retain all Notices.
3.2 You may modify Covered Source, other than Notices, provided that You irrevocably undertake to make that modified Covered Source available from a Source Location should You Convey a Product in circumstances where the recipient does not otherwise receive a copy of the modified Covered Source. In each case subsection 3.3 shall apply.
You may only delete Notices if they are no longer applicable to the corresponding Covered Source as modified by You and You may add additional Notices applicable to Your modifications. Including Covered Source in a larger work is modifying the Covered Source, and the larger work becomes modified Covered Source.
3.3 You may Convey modified Covered Source (with the effect that You shall also become a Licensor) provided that You:
a) retain Notices as required in subsection 3.2;
b) add a Notice to the modified Covered Source stating that You have modified it, with the date and brief description of how You have modified it;
c) add a Source Location Notice for the modified Covered Source if You Convey in circumstances where the recipient does not otherwise receive a copy of the modified Covered Source; and
d) license the modified Covered Source under the terms and conditions of this Licence (or, as set out in subsection 8.3, a later version, if permitted by the licence of the original Covered Source). Such modified Covered Source must be licensed as a whole, but excluding Available Components contained in it, which remain licensed under their own applicable licences.
4 Making and Conveying Products
You may Make Products, and/or Convey them, provided that You either provide each recipient with a copy of the Complete Source or ensure that each recipient is notified of the Source Location of the Complete Source. That Complete Source is Covered Source, and You must accordingly satisfy Your obligations set out in subsection 3.3. If specified in a Notice, the Product must visibly and securely display the Source Location on it or its packaging or documentation in the manner specified in that Notice.
5 Research and Development
You may Convey Covered Source, modified Covered Source or Products to a legal entity carrying out development, testing or quality assurance work on Your behalf provided that the work is performed on terms which prevent the entity from both using the Source or Products for its own internal purposes and Conveying the Source or Products or any modifications to them to any person other than You. Any modifications made by the entity shall be deemed to be made by You pursuant to subsection 3.2.
6 DISCLAIMER AND LIABILITY
6.1 DISCLAIMER OF WARRANTY -- The Covered Source and any Products are provided 'as is' and any express or implied warranties, including, but not limited to, implied warranties of merchantability, of satisfactory quality, non-infringement of third party rights, and fitness for a particular purpose or use are disclaimed in respect of any Source or Product to the maximum extent permitted by law. The Licensor makes no representation that any Source or Product does not or will not infringe any patent, copyright, trade secret or other proprietary right. The entire risk as to the use, quality, and performance of any Source or Product shall be with You and not the Licensor. This disclaimer of warranty is an essential part of this Licence and a condition for the grant of any rights granted under this Licence.
6.2 EXCLUSION AND LIMITATION OF LIABILITY -- The Licensor shall, to the maximum extent permitted by law, have no liability for direct, indirect, special, incidental, consequential, exemplary, punitive or other damages of any character including, without limitation, procurement of substitute goods or services, loss of use, data or profits, or business interruption, however caused and on any theory of contract, warranty, tort (including negligence), product liability or otherwise, arising in any way in relation to the Covered Source, modified Covered Source and/or the Making or Conveyance of a Product, even if advised of the possibility of such damages, and You shall hold the Licensor(s) free and harmless from any liability, costs, damages, fees and expenses, including claims by third parties, in relation to such use.
7 Patents
7.1 Subject to the terms and conditions of this Licence, each Licensor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in subsections 7.2 and 8.4) patent license to Make, have Made, use, offer to sell, sell, import, and otherwise transfer the Covered Source and Products, where such licence applies only to those patent claims licensable by such Licensor that are necessarily infringed by exercising rights under the Covered Source as Conveyed by that Licensor.
7.2 If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Covered Source or a Product constitutes direct or contributory patent infringement, or You seek any declaration that a patent licensed to You under this Licence is invalid or unenforceable then any rights granted to You under this Licence shall terminate as of the date such process is initiated.
8 General
8.1 If any provisions of this Licence are or subsequently become invalid or unenforceable for any reason, the remaining provisions shall remain effective.
8.2 You shall not use any of the name (including acronyms and abbreviations), image, or logo by which the Licensor or CERN is known, except where needed to comply with section 3, or where the use is otherwise allowed by law. Any such permitted use shall be factual and shall not be made so as to suggest any kind of endorsement or implication of involvement by the Licensor or its personnel.
8.3 CERN may publish updated versions and variants of this Licence which it considers to be in the spirit of this version, but may differ in detail to address new problems or concerns. New versions will be published with a unique version number and a variant identifier specifying the variant. If the Licensor has specified that a given variant applies to the Covered Source without specifying a version, You may treat that Covered Source as being released under any version of the CERN-OHL with that variant. If no variant is specified, the Covered Source shall be treated as being released under CERN-OHL-S. The Licensor may also specify that the Covered Source is subject to a specific version of the CERN-OHL or any later version in which case You may apply this or any later version of CERN-OHL with the same variant identifier published by CERN.
8.4 This Licence shall terminate with immediate effect if You fail to comply with any of its terms and conditions.
8.5 However, if You cease all breaches of this Licence, then Your Licence from any Licensor is reinstated unless such Licensor has terminated this Licence by giving You, while You remain in breach, a notice specifying the breach and requiring You to cure it within 30 days, and You have failed to come into compliance in all material respects by the end of the 30 day period. Should You repeat the breach after receipt of a cure notice and subsequent reinstatement, this Licence will terminate immediately and permanently. Section 6 shall continue to apply after any termination.
8.6 This Licence shall not be enforceable except by a Licensor acting as such, and third party beneficiary rights are specifically excluded.
SPDX-License-Identifier: CERN-OHL-S-2.0

59
LICENSE.md Normal file
View File

@@ -0,0 +1,59 @@
# Lizenz Smart Chain Oiler
Dieses Projekt kombiniert Firmware, HardwareDesigns und Dokumentation. Unterschiedliche Bestandteile stehen unter unterschiedlichen, jeweils passenden OpenSourceLizenzen.
---
## Firmware & WebUI (Software)
**Lizenz: GNU General Public License v3 (GPL3.0)**
* Frei nutzbar, veränderbar und weiterverteilbar.
* Änderungen oder Weitergaben müssen ebenfalls unter GPL3.0 veröffentlicht werden.
* Keine kommerzielle Nutzung in ClosedSourceProdukten möglich.
👉 Datei: `COPYING.GPLv3`
---
## PCB & Schaltpläne (Hardware)
**Lizenz: CERN Open Hardware License v2 Strongly Reciprocal (CERNOHLS2.0)**
* Erlaubt Nachbau, Modifikation und Weitergabe.
* Abgeleitete Designs müssen wieder unter derselben Lizenz veröffentlicht werden.
* Kommerzielle Nutzung ist nur erlaubt, wenn die Konstruktionsdateien (Schaltpläne, PCBLayouts, Gerber) offengelegt werden.
👉 Datei: `LICENSE.CERNOHLS2.0`
---
## Dokumentation & Bilder (Manuals, Renderings, Fotos)
**Lizenz: Creative Commons AttributionNonCommercialShareAlike 4.0 (CC BYNCSA 4.0)**
* Frei nutzbar und veränderbar mit Namensnennung.
* **Nichtkommerziell**: keine Nutzung für Verkauf oder gewerbliche Produkte.
* **ShareAlike**: abgeleitete Werke müssen wieder unter derselben Lizenz stehen.
👉 Datei: `LICENSE.CCBYNCSA4.0`
---
## Zusammenfassung
* **Basteln, Nachbauen, Lernen, Forken:** erlaubt ✅
* **Verkauf/kommerzieller Vertrieb ohne Freigabe:** verboten ❌
* **Bei Änderungen/Forks:** immer Quelltexte, Schaltpläne und Doku wieder offenlegen.
---
## Hinweis
Diese Lizenzkombination wurde gewählt, um **Nachbau & Weiterentwicklung** zu fördern, gleichzeitig aber **kommerzielle Ausbeutung ohne Rücksprache** zu verhindern. Für eine kommerzielle Lizenzierung bitte Kontakt mit dem Autor aufnehmen.
---
## Autor
Souko „Shakaru“ Hiabuto 2025

247
README.md
View File

@@ -0,0 +1,247 @@
# Smart Chain Oiler
Ein intelligenter, mikrocontrollergesteuerter Kettenöler für Motorräder. Bedient wird das System mit **nur einem Taster** und einer **RGBLED**. Alle erweiterten Einstellungen und Wartung erfolgen über ein **WebUI** (WiFiAccess Point, plattformunabhängig, keine App nötig). Der reguläre Betrieb läuft komplett autark Smartphone bleibt in der Tasche.
---
## Features
* **Automatische Schmierung**
* Normalmodus: Impuls alle **8000 m** (Standard, anpassbar)
* Regenmodus: Impuls alle **4000 m** (Standard, anpassbar)
* Metergenaue Distanzzählung **über Neustarts hinweg** (setzt nicht auf 0 zurück)
* **Modi**
* **Normal** / **Regen** (per Taster umschaltbar, letzter Modus wird gespeichert)
* **WashMode**: für xym (Standard **500m**) **alle 10m** ein Impuls; danach automatische Rückkehr zum vorherigen Modus
* **Prime/Entlüften**: feste Impulsanzahl (Standard **25 Pulse**) zum Spülen/Entlüften
* **WiFiAP**: Zugriff auf WebUI für Setup, Wartung, Updates
* **Virtuelle Tanküberwachung**
* Details zum Tankmodell & zur Pumpensteuerung siehe weiter unten.
* **Diagnose (DTC) & LiveStatus**
* DTCSchweregrade: **INFO**, **WARN (Orange)**, **CRITICAL (Rot, stoppt Pumpe)**
* Alle DTCs mit Klartext im WebUI; Push via WebSocket
* **Mehrere Geschwindigkeitsquellen**
* **Impuls/Pickup** (Tachosignal)
* **GPS** (seriell; Baudrate wählbar)
* **CAN** (KTMspezifisch)
* **OBD2 über CAN** (in Test)
* **OBD2 über KLine** (ab PCBRev1.4)
* **RGBLED Feedback**
* Farben: Grün (Normal), Blau (Regen), Pink blinkend (Prime), Türkis (Wash), Gelb (AP aktiv), Orange (Warnung), Rot (kritisch)
* Helligkeit **min/max** und Blinkmodus konfigurierbar
* **OTAUpdates**
* OTA (Port 8266, Passwort), mit optionaler OLEDProgressanzeige
* **Dateisystem & Kompatibilität**
* LittleFS mit **„required flash version“**Check; WebUITab zeigt Firmware, Flash und GitVersion
* **EEPROMArchitektur**
* Partitionen **CFG**/**PDS** mit Checksummen, SanityChecks & WearLeveling; passende DTCs bei Inkonsistenzen
---
## Tankmodell & Pumpensteuerung
* **Dosis pro Puls**: einstellbar in µl (Standard auf McCoi-Pumpe abgestimmt)
* **Virtuelles Tankmodell**: berechnet Füllstand und Restreichweite basierend auf Tankgröße und Dosiermenge
* **Warnung & Stopp**: Orange bei niedrigem Füllstand, Rot & Abschaltung bei 0%
* **Prime/Purge**: feste Pulsanzahl (Standard 25), konfigurierbar im WebUI
* **Wash-Mode**: spezielles Muster z.B. alle 10m ein Puls über definierte Gesamtdistanz
* **Pumpen-Timing**: auf die McCoi Spezial-Ölpumpe abgestimmt, für gleichmäßige Dosierung
---
## Hardware
* **MCU:** ESP8266 (Wemos D1 mini, ArduinoFramework)
* **PCB:** Revisionen 1.21.4 (ab **1.4**: OBD2 **KLine**)
* **Pumpe:**
* Ursprünglich **Dellorto Ölpumpe PLE8**
* Aktuell **McCoi SpezialÖlpumpe** **SoftwareAnsteuerung dieses Projekts ist auf diese Pumpe abgestimmt**. Dank hilfreicher Hinweise von Steffen Koberitz (McCoi) zur optimalen Ansteuerung; **keine Mitarbeit** an der PumpenHardwareentwicklung.
* **Option:** I²C OLEDDisplay 128×64 (Standard Arduino/„China“Module)
### Getestete Motorräder
* **KTM 890 Adventure R (2021)**
* **KTM 1290 Super Duke (2023)**
---
## Tankmodell & Pumpensteuerung
*Implementierung: `lubeapp.cpp`*
* **Dosierung (µl/Puls):** konfigurierbar im WebUI (Schlüssel: *amountPerDose\_microL*). Werte und Pulszeit sind **auf die McCoiPumpe abgestimmt**.
* **Virtueller Tank:** Tankgröße (ml) → Füllstand (%) → **Warnschwelle** (Orange) → **0%** stoppt die Pumpe (Rot). TankReset unter **Wartung**.
* **Prime/Purge:** feste Impulsanzahl (Standard **25**), zum Spülen/Entlüften; Start per Taster oder WebUI.
* **WashMode:** ImpulsPattern pro Strecke (Standard: **alle 10m** über **500m**), danach automatische Rückkehr zu Normal/Regen.
* **Persistenz:** Laufende Zähler & Tankstand werden **über Neustarts** mitgeführt (EEPROM/Flash + Sanity/Checksum).
---
## GPSQuelle (seriell)
*Implementierung: `gps.cpp`, TinyGPSPlus*
* **Parser:** TinyGPSPlus; Baudrate im WebUI wählbar.
* **Verwendung:** Geschwindigkeit/Distanz als Basis für Schmierintervalle, metergenau.
* **Fallback & DTC:** Kein GPS → DTCMeldung (je nach Konfiguration WARN/CRIT) und LEDSignalisierung; alternative Quellen (Impuls/CAN/OBD) bleiben nutzbar.
* **Praxis:** Geeignet, wenn kein Pickup/Tachosignal verfügbar ist oder als zusätzliche Prüfinstanz.
---
## Bedienung (Taster & LED)
> **Prinzip:** Taster gedrückt halten → **LEDFarbe beobachten** → bei gewünschter Farbe **loslassen**.
* **0,53,5s**: **Normal ↔ Regen** (Grün/Blau)
* **3,56,5s**: **WashMode** (Türkis)
* **6,59,5s**: **Prime/Entlüften** (Pink blinkend)
* **9,512,5s**: **WiFiAP** an/aus (Gelb)
```mermaid
flowchart LR
A[Button hold] --> B{HoldDauer}
B -->|0.53.5 s| C[Toggle Normal↔Regen]
B -->|3.56.5 s| D[WashMode aktiv]
B -->|6.59.5 s| E[Prime/Entlüften]
B -->|9.512.5 s| F[WiFiAP Toggle]
C --> G[LED: Grün/Blau]
D --> H[LED: Türkis]
E --> I[LED: Pink blinkend]
F --> J[LED: Gelb]
```
**LEDBedeutung (Auswahl):** Grün=Normal · Blau=Regen · Pink blinkend=Prime · Türkis=Wash · Gelb=AP aktiv · Orange=Warnung · Rot=Kritisch (Stopp)
---
## WebUI (WiFiAP)
**Stack:** WebSocket · JavaScript · Bootstrap · jQuery · responsive.
**Tabs & Funktionen:**
* **Home**: Tank % (Progressbar), aktueller Systemstatus, DTCTabelle
* **Wartung**: Tank **zurücksetzen**, Entlüften (Pulsezahl einstellen & starten), **Einmessen** (Pulsecounter), **LiveDebug** (Start/Stop), **Reboot**
* **Einstellungen**:
* **Signalquelle** (Impuls/CAN/GPS/…)
* **Impuls**: Reifenbreite, Verhältnis, Felgendurchmesser, Pulse/Umdrehung
* **CAN**: Modellwahl
* **GPS**: Baudrate
* **Dosierung**: Normal, Regen, Waschdistanz, Waschintervall
* **Öltank**: Kapazität (ml), Warnschwelle (%), Menge/Puls (µl)
* **LED**: Blinkmodus, Min-/MaxBrightness
* **WiFi**: SSIDListe, Passwort, AutoConnect
* **Speichern** (Hinweis: Wechsel der Signalquelle triggert Neustart)
* **Update**:
* Versionen: **Firmware**, **Benötigte FlashVersion**, **Installierte FlashVersion**, **GitRevision**
* **EEPROMBackup** (Download) & **Restore** (Upload `.ee.json`)
* **FirmwareUpdate** (Upload `.fw.bin` oder `.fs.gz`)
> Für den Alltag ist das WebUI nicht nötig; es dient Setup, TankReset und Diagnose/Updates.
### FrontendDateien
* `index.htm` (HauptUI)
* `static/js/websocket.js` (WebSocketClient & LiveUpdate)
* `static/js/script.js` (UIHelpers, z.B. PasswortToggle, FileLabel)
* `static/js/dtc_table.js` + `static/dtc_table.json` (DTCMapping mit Titel & Beschreibung)
* `post.htm` (Zwischenseite nach Speichern/Update)
### WebSocketProtokoll (Client ← Server)
* `NOTIFY:<type>;<message>` → UIToast/Alert
* `DEBUG:<text>` → LiveDebugFenster (append)
* `DTC:<dtcList>` → aktive DTCs, z.B. `ts,code,severity,active;...`
→ UI: **processDTCNotifications** & **fillDTCTable** (Titel/Beschreibung via `dtc_table.json`)
* `MAPPING_STATUS:<map>` → SchlüsselMapping für **STATUS**
* `MAPPING_STATIC:<map>` → SchlüsselMapping für **STATIC**
* `STATUS:<values>` → Laufzeitwerte, in UI gerendert
* `STATIC:<values>` → statische Werte (Konfiguration/Versionen)
> **WebSocketEndpoint:** `ws://<host>/ws`
### WebSocketProtokoll (Client → Server)
* Generischer UIEvent: `btn-<elementId>:<value>`
Beispiel: ButtonKlicks/Bestätigungen senden `btn-…` an den Server.
---
## Build & Flash (PlatformIO)
* **Projekt:** `platformio.ini` mit Environments für PCBRevisionen **1.2**, **1.3**, **1.4** (Serial/OTA)
* **DefaultEnv:** `pcb_rev_1-4_serial`
* **Filesystem:** LittleFS (automatisierte Vorbereitung via Pre/PostScripts)
* **OTA:** `espota` (Port 8266, Passwort aus `wifi_credentials.ini`)
* **GitRevision:** wird als Macro eingebettet (CodegenScript)
* **Libs (Auszug):** U8g2, Adafruit NeoPixel, Ticker, I2C\_EEPROM, ESPAsyncWebServeresphome, ArduinoJson 7, MCP\_CAN, TinyGPSPlus
### Beispiel
```bash
# Firmware bauen (StandardEnv)
pio run
# Seriell flashen (z.B. PCB Rev 1.4)
pio run -e pcb_rev_1-4_serial -t upload
# OTA flashen
pio run -e pcb_rev_1-4_ota -t upload
```
**Konfiguration über BuildFlags** (Auszug):
* `-DPCB_REV=…` (automatisch je nach Env)
* `-DFEATURE_ENABLE_OLED`, `-DATOMIC_FS_UPDATE`, `-DCAN_DEBUG_MESSAGE`
* WiFi/Passwörter via `wifi_credentials.ini` (`WIFI_SSID_CLIENT`, `WIFI_PASSWORD_CLIENT`, `ADMIN_PASSWORD`, `WIFI_AP_PASSWORD`)
### FlashVersion & Updatepfad
* Wenn „**Benötigte FlashVersion**“ ≠ „**Installierte FlashVersion**“: zuerst **FSImage** (`.fs.gz`) im WebUI unter **Update → FirmwareUpdate** hochladen; danach die eigentliche Firmware (`.fw.bin`).
---
## Diagnose (DTC)
* **WARN (Orange)**: Hinweis/Warnung, Betrieb läuft weiter
* **CRITICAL (Rot)**: kritischer Fehler, Öler stoppt
* DTCs erscheinen live im WebUI (Tabelle & DetailModal); zusätzlich LEDSignale
* **Vollständige DTCListe** inkl. Beschreibungen siehe **Manual.md**
---
## Roadmap / Status
* OBD2 über CAN & KLine: **in aktiver Testphase**
* GPSQuelle: **funktionsfähig**, weitere Feldtests
* Weitere Bikes/Modelle: CommunityFeedback willkommen
---
## Lizenz
- **Firmware & WebUI (Software):** [GNU GPLv3](COPYING.GPLv3)
- **PCB & Schaltpläne (Hardware):** [CERN OHL-S v2.0](LICENSE.CERN-OHL-S-2.0)
- **Dokumentation & Bilder:** [CC BY-NC-SA 4.0](LICENSE.CC-BY-NC-SA-4.0)
👉 Zusammenfassung: Basteln, Nachbauen, Lernen erlaubt ✅ kommerzieller Vertrieb oder Closed-Source-Nutzung verboten ❌. Details siehe [LICENSE.md](LICENSE.md).
---
## Autor & Dank
Entwickelt von **Souko „Shakaru“ Hiabuto**
Besonderer Dank an **Steffen Koberitz (McCoi)** für Hinweise zur optimalen Ansteuerung der McCoiPumpe.

3
Software/.gitignore vendored
View File

@@ -3,3 +3,6 @@ data/
.vscode
wifi_credentials.ini
__pycache__
# Node-Tools für Build-Scripts
/tools_node/
/data_stripped/

View File

@@ -11,23 +11,41 @@ import platform
Import("env")
Import("projenv")
# Überprüfe die Betriebssystemplattform
if platform.system() == "Windows":
# Setze die Pfade zu den Tools für Windows
html_minifier_path = os.path.join(os.getenv("APPDATA"), "npm", "html-minifier.cmd")
uglifyjs_path = os.path.join(os.getenv("APPDATA"), "npm", "uglifyjs.cmd")
terser_path = os.path.join(os.getenv("APPDATA"), "npm", "terser.cmd")
cssnano_path = os.path.join(os.getenv("APPDATA"), "npm", "cssnano.cmd")
elif platform.system() == "Linux":
# Setze die Namen der Tools für Linux
html_minifier_path = "html-minifier"
uglifyjs_path = "uglifyjs"
terser_path = "terser"
cssnano_path = "cssnano"
else:
# Hier könntest du weitere Bedingungen für andere Betriebssysteme hinzufügen
raise Exception("Unterstütztes Betriebssystem nicht erkannt")
def ensure_node_tool(package_name, binary_name=None):
"""Installiert das Tool lokal, wenn es fehlt mit npm init bei Bedarf"""
if binary_name is None:
binary_name = package_name
project_dir = env.subst('$PROJECT_DIR')
tools_dir = os.path.join(project_dir, 'tools_node')
local_bin = os.path.join(tools_dir, 'node_modules', '.bin', binary_name)
os.makedirs(tools_dir, exist_ok=True)
# Wenn Binary schon vorhanden ist, einfach zurückgeben
if os.path.isfile(local_bin):
return local_bin
print(f"🛠️ Installing missing node tool: {package_name}")
# Initialisiere npm, falls noch nicht geschehen
if not os.path.isfile(os.path.join(tools_dir, 'package.json')):
print("📦 Initializing local npm project...")
subprocess.run(['npm', 'init', '-y'], cwd=tools_dir, check=True)
try:
subprocess.run(['npm', 'install', package_name], cwd=tools_dir, check=True)
except Exception as e:
print(f"❌ Fehler beim Installieren von {package_name}: {e}")
return binary_name # Fallback: globale binary
return local_bin if os.path.isfile(local_bin) else binary_name
# Tools sicherstellen
# Tools sicherstellen Package-Name und CLI-Binary ggf. unterschiedlich
html_minifier_path = ensure_node_tool("html-minifier")
terser_path = ensure_node_tool("terser")
cssnano_path = ensure_node_tool("cssnano-cli", "cssnano")
def minify_html(input_path, output_path):
subprocess.run([html_minifier_path, '--collapse-whitespace', '--remove-comments', input_path, '-o', output_path])
@@ -40,13 +58,7 @@ def minify_css(input_path, output_path):
def process_file(src_path, dest_path):
_, file_extension = os.path.splitext(src_path)
# Extrahiere den Ordnerpfad im Zielverzeichnis
dest_dir = os.path.dirname(dest_path)
# Erstelle den Ordner und alle dazugehörigen Unterordner, falls sie nicht existieren
os.makedirs(dest_dir, exist_ok=True)
os.makedirs(os.path.dirname(dest_path), exist_ok=True)
if file_extension.lower() == '.js':
minify_js(src_path, dest_path)
elif file_extension.lower() == '.css':
@@ -54,128 +66,89 @@ def process_file(src_path, dest_path):
elif file_extension.lower() in ['.html', '.htm']:
minify_html(src_path, dest_path)
else:
# Kopiere nicht bearbeitbare Dateien direkt in den Zielordner
shutil.copy2(src_path, dest_path)
def strip_files(src_dir, dest_dir):
# Erstelle den Zielordner und alle dazugehörigen Unterordner, falls sie nicht existieren
os.makedirs(dest_dir, exist_ok=True)
# Durchlaufe alle Dateien und Unterverzeichnisse im Quellordner
for root, _, files in os.walk(src_dir):
for filename in files:
src_path = os.path.join(root, filename)
dest_path = os.path.relpath(src_path, src_dir)
dest_path = os.path.join(dest_dir, dest_path)
# Verarbeite nur Dateien (keine Unterverzeichnisse)
rel_path = os.path.relpath(src_path, src_dir)
dest_path = os.path.join(dest_dir, rel_path)
process_file(src_path, dest_path)
def gzip_file(src_path, dst_path):
with open(src_path, 'rb') as src, gzip.open(dst_path, 'wb') as dst:
for chunk in iter(lambda: src.read(4096), b""):
dst.write(chunk)
def getListOfFiles(dirName):
# create a list of file and sub directories
# names in the given directory
listOfFile = os.listdir(dirName)
allFiles = list()
# Iterate over all the entries
for entry in listOfFile:
# Create full path
entries = os.listdir(dirName)
allFiles = []
for entry in entries:
fullPath = os.path.join(dirName, entry)
# If entry is a directory then get the list of files in this directory
if os.path.isdir(fullPath):
allFiles = allFiles + getListOfFiles(fullPath)
allFiles += getListOfFiles(fullPath)
else:
allFiles.append(fullPath)
return allFiles
def remove_prefix(text, prefix):
if text.startswith(prefix):
return text[len(prefix):]
return text # or whatever
# Compress files from 'data_src/' to 'data/'
def safe_relpath(path, start):
return os.path.relpath(path, start).replace("\\", "/")
def gzip_webfiles(source, target, env):
# Filetypes to compress
filetypes_to_gzip = ['.css', '.png', '.js', '.ico', '.woff2', '.json']
print('\nGZIP: Starting gzip-Process for LittleFS-Image...\n')
data_src_dir_path = os.path.join(env.get('PROJECT_DIR'), 'data_src')
data_temp_dir_path = os.path.join(env.get('PROJECT_DIR'), 'data_stripped')
strip_files(data_src_dir_path, data_temp_dir_path)
data_dir_path = env.get('PROJECT_DATA_DIR')
# check if data and datasrc exist. If the first exists and not the second, it renames it
if(os.path.exists(data_dir_path) and not os.path.exists(data_temp_dir_path)):
print('GZIP: Directory "'+data_dir_path +
'" exists, "'+data_temp_dir_path+'" is not found.')
print('GZIP: Renaming "' + data_dir_path +
'" to "' + data_temp_dir_path + '"')
os.rename(data_dir_path, data_temp_dir_path)
# Delete the 'data' directory
if(os.path.exists(data_dir_path)):
print('GZIP: Deleting the "data" directory ' + data_dir_path)
shutil.rmtree(data_dir_path)
# Recreate empty 'data' directory
print('GZIP: Re-creating an empty data directory ' + data_dir_path)
os.mkdir(data_dir_path)
# Determine the files to compress
src_dir = os.path.join(env.get('PROJECT_DIR'), 'data_src')
temp_dir = os.path.join(env.get('PROJECT_DIR'), 'data_stripped')
dst_dir = env.get('PROJECT_DATA_DIR')
strip_files(src_dir, temp_dir)
if os.path.exists(dst_dir):
shutil.rmtree(dst_dir)
os.mkdir(dst_dir)
files_to_copy = []
files_to_gzip = []
all_data_src = getListOfFiles(data_temp_dir_path)
for file in all_data_src:
file_name, file_extension = os.path.splitext(file)
print(file_name + " has filetype " + file_extension)
if file_extension in filetypes_to_gzip:
for file in getListOfFiles(temp_dir):
_, ext = os.path.splitext(file)
if ext in filetypes_to_gzip:
files_to_gzip.append(file)
else:
filename_subdir = remove_prefix(file, data_temp_dir_path)
files_to_copy.append(filename_subdir)
files_to_copy.append(safe_relpath(file, temp_dir))
for file in files_to_copy:
print('GZIP: Copying file from: ' + data_temp_dir_path + file + ' to: ' + data_dir_path + file)
os.makedirs(os.path.dirname(data_dir_path + file), exist_ok=True)
shutil.copy(data_temp_dir_path + file, data_dir_path + file)
# Compress and move files
full_dst = os.path.join(dst_dir, file)
os.makedirs(os.path.dirname(full_dst), exist_ok=True)
shutil.copy(os.path.join(temp_dir, file), full_dst)
was_error = False
try:
for source_file_path in files_to_gzip:
print('GZIP: compressing... ' + source_file_path)
filename_subdir = remove_prefix(source_file_path, data_temp_dir_path)
target_file_path = data_dir_path + filename_subdir
os.makedirs(os.path.dirname(target_file_path), exist_ok=True)
print('GZIP: Compressed... ' + target_file_path)
gzip_file(source_file_path, target_file_path + ".gz")
for src in files_to_gzip:
rel_path = safe_relpath(src, temp_dir)
dst_path = os.path.join(dst_dir, rel_path + '.gz')
os.makedirs(os.path.dirname(dst_path), exist_ok=True)
print('GZIP: compressing... ' + rel_path)
gzip_file(src, dst_path)
except IOError as e:
was_error = True
print('GZIP: Failed to compress file: ' + source_file_path)
# print( 'GZIP: EXCEPTION... {}'.format( e ) )
if was_error:
print('GZIP: Failure/Incomplete.\n')
else:
print('GZIP: Compressed correctly.\n')
shutil.rmtree(data_temp_dir_path)
print('GZIP: Fehler beim Komprimieren:', e)
return
if was_error:
print('⚠️ GZIP: Nicht alle Dateien konnten verarbeitet werden.\n')
else:
print('✅ GZIP: Komprimierung abgeschlossen.\n')
shutil.rmtree(temp_dir)
def gzip_binffiles(source, target, env):
littlefsbin = target[0].get_abspath()
targetbin = os.path.join(os.path.dirname(littlefsbin), 'filesystem.fs')
shutil.copyfile(littlefsbin, targetbin)
gzip_file(targetbin, os.path.join(str(targetbin) + '.gz'))
os.remove(targetbin)
return
tmpbin = os.path.join(os.path.dirname(littlefsbin), 'filesystem.fs')
shutil.copyfile(littlefsbin, tmpbin)
gzip_file(tmpbin, tmpbin + '.gz')
os.remove(tmpbin)
# IMPORTANT, this needs to be added to call the routine
# Hooks setzen
env.AddPreAction('$BUILD_DIR/littlefs.bin', gzip_webfiles)
env.AddPostAction('$BUILD_DIR/littlefs.bin', gzip_binffiles)

View File

@@ -8,11 +8,11 @@
<link rel="stylesheet" href="static/css/bootstrap.min.css">
<link rel="stylesheet" href="static/css/custom.css">
<link rel="stylesheet" href="static/css/tweaks.css">
<script src="static/js/jquery.min.js"></script>
<script src="static/js/bootstrap.min.js"></script>
<script src="static/js/websocket.js"></script>
<script src="static/js/dtc_table.js"></script>
<script src="static/js/script.js"></script>
<script src="static/js/jquery.min.js" defer></script>
<script src="static/js/bootstrap.min.js" defer></script>
<script src="static/js/websocket.js" defer></script>
<script src="static/js/dtc_table.js" defer></script>
<script src="static/js/script.js" defer></script>
<link rel="apple-touch-icon" sizes="180x180" href="static/img/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="static/img/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="static/img/favicon-16x16.png">
@@ -217,9 +217,6 @@
<label for="speedsource" class="control-label col-4">Schnittstelle</label>
<div class="col-8">
<select id="speedsource" class="set-wsevent data-speedsource select form-control">
<option value="Impuls">Impuls</option>
<option value="GPS">GPS</option>
<option value="CAN-Bus">CAN-Bus</option>
</select>
</div>
</div>
@@ -298,8 +295,6 @@
<label for="cansource" class="control-label col-4">Model</label>
<div class="col-8">
<select id="cansource" class="set-wsevent data-cansource select form-control">
<option value="KTM 890 Adventure R (2021)">KTM 890 Adventure R (2021)</option>
<option value="KTM 1290 Superduke R (2023)">KTM 1290 Superduke R (2023)</option>
</select>
</div>
</div>
@@ -349,6 +344,33 @@
</div>
</div>
</div>
<div class="form-group row">
<label for="washdistance" class="control-label col-4">Waschmodus Distanz</label>
<div class="col-8">
<div class="input-group">
<input id="washdistance" type="text"
class="set-wsevent data-washdistance form-control" required="required">
<div class="input-group-append">
<span class="input-group-text">m</span>
</div>
</div>
</div>
</div>
<div class="form-group row">
<label for="washinterval" class="control-label col-4">Waschmodus Interval</label>
<div class="col-8">
<div class="input-group">
<input id="washinterval" type="text"
class="set-wsevent data-washinterval form-control" required="required">
<div class="input-group-append">
<span class="input-group-text">m</span>
</div>
</div>
</div>
</div>
</p>
<!-- Div Group Lube Settings-->
<!-- Div Group Oiltank Settings -->
@@ -483,21 +505,26 @@
<table class="table">
<tbody>
<tr>
<th class="col-7" scope="col">Parameter</td>
<th class="col-5" scope="col">Value</td>
<th class="col-7" scope="col">Parameter</th>
<th class="col-5" scope="col">Value</th>
</tr>
<tr>
<td>Firmware Version</td>
<td>%SW_VERSION%</td>
<td class="data-fw-version"></td>
</tr>
<tr>
<td>Flash Version</td>
<td>%FS_VERSION%</td>
<td>Benötigte Flash Version</td>
<td class="data-req-flash-version"></td>
</tr>
<tr>
<td>Installierte Flash Version</td>
<td class="data-flash-version"></td>
</tr>
<tr>
<td>Git Revision</td>
<td>%GIT_REV%</td>
<td class="data-git-rev"></td>
</tr>
</tbody>
</table>
</p>
<!-- Div Group VersionInfo -->

View File

@@ -84,7 +84,6 @@ function onMessage(event) {
processDTCNotifications(dtcArray);
fillDTCTable(dtcArray);
} else if (data.startsWith("MAPPING_STATUS:")) {
const data_sliced = data.slice(15);
statusMapping = createMapping(data_sliced);
@@ -100,19 +99,15 @@ function onMessage(event) {
const data_sliced = data.slice(7);
const result = processDataString(data_sliced, staticMapping);
fillValuesToHTML(result);
console.log(result);
overlay.style.display = "none";
}
}
function createMapping(mappingString) {
const mappingArray = mappingString.split(";");
const mapping = [];
mappingArray.forEach((variable) => {
if (variable !== null) mapping.push(variable.trim());
});
return mapping;
return mappingString
.split(";")
.map((s) => s.trim())
.filter((s) => s !== "");
}
function processDataString(dataString, mapping) {
@@ -157,43 +152,136 @@ function do_resize(textbox) {
else textbox.rows = rows;
}
function fillValuesToHTML(dataset) {
for (var key in dataset) {
var key_prefixed = "data-" + key;
var elements = document.getElementsByClassName(key_prefixed);
// --- Globale Puffer für Select-Handling ---
const selectDesiredValue = Object.create(null); // keyBase -> desired value ("speedsource" -> "GPS")
const selectOptionsReady = Object.create(null); // keyBase -> true/false
if (elements.length > 0) {
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
function splitCsv(s) {
return (s || "")
.split(",")
.map((x) => x.trim())
.filter(Boolean);
}
if (element.type === "checkbox") {
// Wenn das Element ein Kontrollkästchen ist
element.checked = dataset[key] == 1 ? true : false;
} else if (element.tagName === "SELECT") {
// Wenn das Element ein Dropdown ist
setDropdownValue(element, dataset[key]);
} else if (element.classList.contains("progress-bar")) {
// Wenn das Element eine Fortschrittsleiste ist
updateProgressBar(element, dataset[key]);
} else if (element.classList.contains("hideable")) {
// Wenn das Element ein Settingsabschnitt-div ist
if (dataset[key] == 0) element.style.display = "none";
else element.style.display = "";
} else {
// Standardmäßig für Textfelder und andere Elemente
element.value = dataset[key];
}
}
}
function hasOption(selectEl, value) {
for (let i = 0; i < selectEl.options.length; i++) {
if (selectEl.options[i].value === value) return true;
}
return false;
}
function addOption(selectEl, value, selectIt = false) {
const o = document.createElement("option");
o.value = value;
o.textContent = value;
selectEl.appendChild(o);
if (selectIt) {
selectEl.value = value;
}
}
// Funktion zum Setzen des ausgewählten Werts für Dropdowns
function populateSelect(selectId, options, currentValue) {
const sel = document.getElementById(selectId);
if (!sel) return;
// 1) komplett ersetzen
sel.innerHTML = "";
options.forEach((opt) => addOption(sel, opt, false));
// 2) Zielwert bestimmen (currentValue > bereits gepuffert > vorhandener Wert > erste Option)
const wanted =
(currentValue && currentValue.length ? currentValue : null) ??
selectDesiredValue[selectId] ??
sel.value ??
(options[0] || "");
// 3) Falls gewünschte Option fehlt, hinzufügen
if (wanted && !hasOption(sel, wanted)) addOption(sel, wanted, false);
// 4) Setzen
sel.value = wanted;
// 5) Markieren: Optionen sind ready
selectOptionsReady[selectId] = true;
// Verbrauchte Wunschwerte löschen
delete selectDesiredValue[selectId];
}
// Robust: setzt den Wert; wenn Option fehlt, füge sie hinzu
function setDropdownValue(selectElement, value) {
for (var i = 0; i < selectElement.options.length; i++) {
if (selectElement.options[i].value === value) {
selectElement.selectedIndex = i;
break;
if (!value) return;
if (!hasOption(selectElement, value)) {
addOption(selectElement, value, false);
}
selectElement.value = value;
}
// Core: schreibt Werte in DOM, erkennt *-options und füllt Selects
function fillValuesToHTML(dataset) {
for (const key in dataset) {
const val = dataset[key];
// A) Optionen-Feld? (z.B. "speedsource-options")
if (key.endsWith("-options")) {
const base = key.slice(0, -"-options".length); // "speedsource"
const selectId = base; // ID = keyBase
populateSelect(
selectId,
splitCsv(val),
selectDesiredValue[selectId] || undefined
);
continue; // fertig mit diesem key
}
// B) Normales Feld
const key_prefixed = "data-" + key;
const elements = document.getElementsByClassName(key_prefixed);
if (elements.length === 0) continue;
for (let i = 0; i < elements.length; i++) {
const el = elements[i];
// Checkbox?
if (el.type === "checkbox") {
el.checked = val == 1;
continue;
}
// Select?
if (el.tagName === "SELECT") {
const selectId = el.id || key; // ID hat Vorrang, sonst key
// Wenn die Optionen für dieses Select noch NICHT bereit sind, Wunschwert puffern
if (!selectOptionsReady[selectId]) {
selectDesiredValue[selectId] = val;
// Sicherheitsnetz: falls doch schon Optionen existieren, sofort setzen
setDropdownValue(el, val);
} else {
// Optionen sind ready -> ganz normal setzen (ggf. Option ergänzen)
setDropdownValue(el, val);
}
continue;
}
// Progress-Bar?
if (el.classList.contains("progress-bar")) {
updateProgressBar(el, val);
continue;
}
// Hideable-Section?
if (el.classList.contains("hideable")) {
el.style.display = val == 0 ? "none" : "";
continue;
}
// Input/Textarea?
if ("value" in el) {
el.value = val;
continue;
}
// Fallback: content nodes (td, span, div)
el.textContent = val;
}
}
}
@@ -212,15 +300,15 @@ function showNotification(message, type) {
// Erstellen Sie ein Bootstrap-Alert-Element
var alertElement = $(
'<div class="alert alert-' +
type +
' alert-dismissible fade show notification" role="alert">' +
"<strong>" +
message +
"</strong>" +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<span aria-hidden="true">&times;</span>' +
"</button>" +
"</div>"
type +
' alert-dismissible fade show notification" role="alert">' +
"<strong>" +
message +
"</strong>" +
'<button type="button" class="close" data-dismiss="alert" aria-label="Close">' +
'<span aria-hidden="true">&times;</span>' +
"</button>" +
"</div>"
);
// Fügen Sie das Alert-Element dem Container hinzu

View File

@@ -0,0 +1,18 @@
// === button_actions.h ===
#ifndef _BUTTON_ACTIONS_H_
#define _BUTTON_ACTIONS_H_
#include <Arduino.h>
#include "buttoncontrol.h"
// Deklarationen der Button-Callbacks
void ButtonAction_ToggleMode();
void ButtonAction_StartPurge();
void ButtonAction_ToggleWiFi();
void ButtonAction_WashMode();
// Bereitstellung der Aktionsliste
extern const ButtonActionEntry buttonActions[];
extern const uint8_t buttonActionCount;
#endif

View File

@@ -0,0 +1,30 @@
// === buttoncontrol.h ===
#ifndef _BUTTONCONTROL_H_
#define _BUTTONCONTROL_H_
#include <Arduino.h>
// Aktionen, die vom Button ausgelöst werden können
enum ButtonAction
{
BTN_NONE,
BTN_CUSTOM
};
// Callback-Funktionstyp
typedef void (*ButtonCallback)();
struct ButtonActionEntry
{
uint32_t holdTimeMs;
uint32_t ledColor;
ButtonCallback callback;
};
// Initialisierung des Buttonmoduls
void ButtonControl_Init(uint8_t pin, const ButtonActionEntry *actions, uint8_t actionCount);
// Muss regelmäßig in loop() aufgerufen werden
void ButtonControl_Update();
#endif

View File

@@ -41,9 +41,10 @@
#elif PCB_REV == 4
#define GPIO_BUTTON D4
#define GPIO_LED D3
#define GPIO_TRIGGER D6
#define GPIO_TRIGGER D8
#define GPIO_PUMP D0
#define GPIO_CS_CAN D8
#define GPIO_CE_KLINE D8
#endif
#ifndef HOST_NAME
@@ -72,6 +73,7 @@ typedef enum eSystem_Status
sysStat_Startup,
sysStat_Normal,
sysStat_Rain,
sysStat_Wash,
sysStat_Purge,
sysStat_Error,
sysStat_Shutdown

View File

@@ -21,7 +21,7 @@
#include "dtc.h"
#include "common.h"
#define EEPROM_STRUCTURE_REVISION 3 // Increment this version when changing EEPROM structures
#define EEPROM_STRUCTURE_REVISION 4 // Increment this version when changing EEPROM structures
#if PCB_REV == 1 || PCB_REV == 2 || PCB_REV == 3
#define EEPROM_SIZE_BYTES I2C_DEVICESIZE_24LC64
@@ -69,6 +69,8 @@ typedef struct
uint32_t RimDiameter_Inch;
uint32_t DistancePerRevolution_mm;
uint16_t BleedingPulses;
uint16_t WashMode_Distance;
uint16_t WashMode_Interval;
SpeedSource_t SpeedSource;
GPSBaudRate_t GPSBaudRate;
CANSource_t CANSource;
@@ -85,7 +87,7 @@ typedef struct
// Default configuration settings
const LubeConfig_t LubeConfig_defaults = {
0, 8000, 4000, 320, DEFAULT_PUMP_DOSE, 30, 1, 150, 70, 18, 2000, 25, SOURCE_IMPULSE,
0, 8000, 4000, 320, DEFAULT_PUMP_DOSE, 30, 1, 150, 70, 18, 2000, 25, 500, 10, SOURCE_IMPULSE,
BAUD_115200,
KTM_890_ADV_R_2021,
false,

View File

@@ -16,19 +16,6 @@
#include <Arduino.h>
#include "webui.h"
const char PROGMEM helpCmd[] = "sysinfo - System Info\n"
"netinfo - WiFi Info\n"
"formatPDS - Format Persistence EEPROM Data\n"
"formatCFG - Format Configuration EEPROM Data\n"
"checkEE - Check EEPROM with checksum\n"
"dumpEE1k - dump the first 1kb of EEPROM to Serial\n"
"dumpEE - dump the whole EPPROM to Serial\n"
"resetPageEE - Reset the PersistenceData Page\n"
"dumpCFG - print Config struct\n"
"dumpPDS - print PersistanceStruct\n"
"saveEE - save EE-Data\n"
"showdtc - Show all DTCs\n"
"dumpGlobals - print globals\n";
typedef enum DebugStatus_e
{
@@ -49,6 +36,13 @@ const char sDebugPorts[dbg_cntElements][7] = {
extern DebugStatus_t DebuggerStatus[dbg_cntElements];
enum LogLevel
{
LOG_INFO,
LOG_WARN,
LOG_ERROR
};
void initDebugger();
void pushCANDebug(uint32_t id, uint8_t dlc, uint8_t *data);
void Debug_pushMessage(const char *format, ...);

View File

@@ -24,7 +24,7 @@ typedef struct Globals_s
tSystem_Status resumeStatus = sysStat_Startup; /**< Status to resume after rain mode */
char systemStatustxt[16] = ""; /**< Text representation of system status */
uint16_t purgePulses = 0; /**< Number of purge pulses */
EERequest_t requestEEAction = EE_IDLE;; /**< EEPROM-related request */
EERequest_t requestEEAction = EE_IDLE; /**< EEPROM-related request */
char DeviceName[33]; /**< Device name */
char FlashVersion[10]; /**< Flash version */
uint16_t eePersistanceAdress; /**< EEPROM persistence address */
@@ -33,6 +33,7 @@ typedef struct Globals_s
bool measurementActive; /**< Flag indicating active measurement */
uint32_t measuredPulses; /**< Number of measured pulses */
bool toggle_wifi;
uint16_t isr_debug;
} Globals_t;
extern Globals_t globals; /**< Global variable struct */

View File

@@ -37,9 +37,10 @@
#define LED_STARTUP_TANKWARN COLOR_AMBER
#define LED_NORMAL_COLOR COLOR_GREEN
#define LED_RAIN_COLOR COLOR_BLUE
#define LED_WIFI_BLINK COLOR_YELLOW
#define LED_WASH_COLOR COLOR_JADE
#define LED_WIFI_COLOR COLOR_YELLOW
#define LED_PURGE_COLOR COLOR_MAGENTA
#define LED_ERROR_BLINK COLOR_RED
#define LED_SHUTDOWN_BLINK COLOR_CYAN
#define LED_ERROR_COLOR COLOR_RED
#define LED_SHUTDOWN_COLOR COLOR_CYAN
#endif /* _LED_COLORS_H_ */

View File

@@ -0,0 +1,35 @@
// === ledcontrol.h ===
#ifndef _LEDCONTROL_H_
#define _LEDCONTROL_H_
#include <Arduino.h>
#include "led_colors.h"
// LED-Muster
enum LedPattern
{
LED_PATTERN_ON,
LED_PATTERN_FLASH,
LED_PATTERN_FLASH_FAST,
LED_PATTERN_BLINK,
LED_PATTERN_BLINK_FAST,
LED_PATTERN_BREATH,
LED_PATTERN_BREATH_REVERSE
};
// Initialisiert die LED-Steuerung
void LEDControl_Init(uint8_t pin);
// Setzt den Basiszustand (Farbe + Pattern), wird verwendet wenn kein Override aktiv ist
void LEDControl_SetBasic(uint32_t color, LedPattern pattern);
// Setzt ein Override mit Timeout (0 = bis explizit gecleart)
void LEDControl_SetOverride(uint32_t color, LedPattern pattern, uint32_t durationMs);
// Hebt das Override wieder auf
void LEDControl_ClearOverride();
// Muss regelmäßig aus loop() aufgerufen werden
void LEDControl_Update();
#endif

View File

@@ -3,10 +3,10 @@
*
* @brief Header file for converting structs to JSON objects.
*
* @note This file is auto-generated by a script on 2024-01-30 20:29:34.
* @note This file is auto-generated by a script on 2025-06-15 11:37:51.
*
* @author Marcel Peterkau
* @date 30.01.2024
* @date 15.06.2025
*/
#ifndef _STRUCT2JSON_H_
@@ -23,4 +23,4 @@ void generateJsonObject_PersistenceData(JsonObject data);
#endif /* _STRUCT2JSON_H_ */
// CODEGENERATOR_CHECKSUM: 59f35aadffd0bbef253210ea2fbaaf9a515553a2e3cc9bf4cfa2819b63c969ce
// CODEGENERATOR_CHECKSUM: 4702cb49ea55617cbb34715164810bb58d3c3f46fb1653b6f47bd4fd9cb0031e

View File

@@ -11,7 +11,7 @@
[platformio]
extra_configs =
wifi_credentials.ini
default_envs = pcb_rev_1-3_serial, pcb_rev_1-3_ota, pcb_rev_1-2_serial, pcb_rev_1-2_ota
default_envs = pcb_rev_1-4_serial
[env]
platform = espressif8266
@@ -42,15 +42,36 @@ monitor_speed = 115200
lib_ldf_mode = deep
lib_deps =
olikraus/U8g2 @ ^2.35.9
adafruit/Adafruit NeoPixel @ ^1.12.0
olikraus/U8g2 @ ^2.36.5
adafruit/Adafruit NeoPixel @ ^1.15.1
sstaub/Ticker @ ^4.4.0
robtillaart/I2C_EEPROM @ ^1.8.2
esphome/ESPAsyncWebServer-esphome @ 3.1.0
bblanchon/ArduinoJson @ ^7.0.1
coryjfowler/mcp_can @ ^1.5.0
mikalhart/TinyGPSPlus @ ^1.0.3
robtillaart/I2C_EEPROM @ ^1.9.2
esphome/ESPAsyncWebServer-esphome @ 3.3.0
bblanchon/ArduinoJson @ ^7.4.1
coryjfowler/mcp_can @ ^1.5.1
mikalhart/TinyGPSPlus @ ^1.1.0
[env:pcb_rev_1-4_serial]
extends = env
custom_pcb_revision = 4
upload_protocol = esptool
build_flags =
${env.build_flags}
-DPCB_REV=${this.custom_pcb_revision}
board_build.ldscript = eagle.flash.4m1m.ld
[env:pcb_rev_1-4_ota]
extends = env
custom_pcb_revision = 4
upload_protocol = espota
upload_port = 10.0.1.14
upload_flags =
--port=8266
--auth=${wifi_cred.admin_password}
build_flags =
${env.build_flags}
-DPCB_REV=${this.custom_pcb_revision}
board_build.ldscript = eagle.flash.4m1m.ld
[env:pcb_rev_1-3_serial]
extends = env

View File

@@ -0,0 +1,46 @@
// === button_actions.cpp ===
#include "button_actions.h"
#include "globals.h"
#include "debugger.h"
#include "led_colors.h"
void ButtonAction_ToggleMode()
{
if (globals.systemStatus == sysStat_Normal)
{
globals.systemStatus = sysStat_Rain;
}
else if (globals.systemStatus == sysStat_Rain)
{
globals.systemStatus = sysStat_Normal;
}
Debug_pushMessage("Toggling Mode\n");
}
void ButtonAction_StartPurge()
{
globals.systemStatus = sysStat_Purge;
Debug_pushMessage("Starting Purge\n");
}
void ButtonAction_ToggleWiFi()
{
globals.toggle_wifi = true;
Debug_pushMessage("Toggling WiFi\n");
}
void ButtonAction_WashMode()
{
globals.systemStatus = sysStat_Wash;
Debug_pushMessage("Setting WashMode\n");
}
// Liste der Aktionen, sortiert nach Mindest-Haltezeit (ms)
const ButtonActionEntry buttonActions[] = {
{500, LED_RAIN_COLOR, ButtonAction_ToggleMode},
{3500, LED_WASH_COLOR, ButtonAction_WashMode},
{6500, LED_PURGE_COLOR, ButtonAction_StartPurge},
{9500, LED_WIFI_COLOR, ButtonAction_ToggleWiFi},
};
const uint8_t buttonActionCount = sizeof(buttonActions) / sizeof(ButtonActionEntry);

View File

@@ -0,0 +1,64 @@
// === buttoncontrol.cpp ===
#include "buttoncontrol.h"
#include "ledcontrol.h"
static uint8_t btnPin;
static uint32_t pressStart = 0;
static bool pressed = false;
static const ButtonActionEntry *btnActions = nullptr;
static uint8_t btnActionCount = 0;
static uint8_t currentActionIndex = 0xFF;
static uint32_t lastColor = 0;
void ButtonControl_Init(uint8_t pin, const ButtonActionEntry *actions, uint8_t actionCount)
{
btnPin = pin;
pinMode(btnPin, INPUT_PULLUP);
btnActions = actions;
btnActionCount = actionCount;
}
void ButtonControl_Update()
{
bool currentState = digitalRead(btnPin) == LOW;
uint32_t now = millis();
if (currentState && !pressed)
{
pressStart = now;
pressed = true;
currentActionIndex = 0xFF;
lastColor = 0;
}
else if (currentState && pressed)
{
uint32_t duration = now - pressStart;
// Finde passende Aktion basierend auf Zeit
for (uint8_t i = 0; i < btnActionCount; i++)
{
if (duration >= btnActions[i].holdTimeMs)
{
if (currentActionIndex != i)
{
currentActionIndex = i;
lastColor = btnActions[i].ledColor;
// Farbe + Pattern setzen
LEDControl_SetOverride(lastColor, LED_PATTERN_BREATH, 0); // Kein Timeout, wird bei Release beendet
}
}
}
}
else if (!currentState && pressed)
{
pressed = false;
if (currentActionIndex != 0xFF && currentActionIndex < btnActionCount)
{
if (btnActions[currentActionIndex].callback)
{
btnActions[currentActionIndex].callback();
}
}
LEDControl_ClearOverride(); // Override-Modus zurücksetzen
}
}

View File

@@ -12,8 +12,10 @@
*/
#include "debugger.h"
DebugStatus_t DebuggerStatus[dbg_cntElements];
#include <map>
#include <functional>
#include <vector>
#include <type_traits>
void processCmdDebug(String command);
void Debug_formatCFG();
@@ -27,7 +29,11 @@ void Debug_ShowDTCs();
void Debug_dumpGlobals();
void Debug_printHelp();
void Debug_Purge();
void Debug_refillTank();
const char *uint32_to_binary_string(uint32_t num);
template<typename T>
void RegisterDebugPrintAuto(const T* ptr, const String& name, uint32_t interval_ms, uint32_t duration_ms);
void Debug_UpdateWatches();
/**
* @brief Initializes the debugger by setting the initial status for different debug ports.
@@ -94,10 +100,10 @@ void Debug_Process()
}
// Check for input buffer overflow
if (inputCnt > sizeof(inputBuffer))
if (inputCnt >= sizeof(inputBuffer) - 1)
{
inputBuffer[sizeof(inputBuffer) - 1] = '\0';
inputCnt = 0;
inputBuffer[sizeof(inputBuffer) - 1] = 0; // terminate the String
InputProcessed = CMD_OVERFLOW;
}
}
@@ -125,7 +131,11 @@ void Debug_Process()
Serial.print(">");
InputProcessed = IDLE;
Debug_UpdateWatches();
}
/**
* @brief Sets the status of a specific debug port (Serial or WebUI).
* Updates the status in the DebuggerStatus array and provides debug messages.
@@ -147,6 +157,27 @@ void SetDebugportStatus(DebugPorts_t port, DebugStatus_t status)
Debug_pushMessage("Enabled DebugPort %s\n", sDebugPorts[port]);
}
void Debug_log(LogLevel level, const char *format, ...)
{
if ((DebuggerStatus[dbg_Serial] == enabled) || (DebuggerStatus[dbg_Webui] == enabled))
{
char buff[128];
va_list arg;
va_start(arg, format);
vsnprintf(buff, sizeof(buff), format, arg);
va_end(arg);
if (DebuggerStatus[dbg_Serial] == enabled)
{
Serial.print(buff);
}
if (DebuggerStatus[dbg_Webui] == enabled)
{
Websocket_PushLiveDebug(String(buff));
}
}
}
/**
* @brief Pushes a formatted debug message to the enabled debug ports (Serial or WebUI).
*
@@ -218,68 +249,137 @@ void pushCANDebug(uint32_t id, uint8_t dlc, uint8_t *data)
}
}
/**
* @brief Processes a debug command and performs corresponding actions.
*
* @param command The debug command to be processed.
*/
void processCmdDebug(String command)
// === splitArgs Helper ===
std::vector<String> splitArgs(const String &input)
{
// Check the received command and execute corresponding actions
if (command == "help")
Debug_printHelp();
else if (command == "sysinfo")
Debug_printSystemInfo();
else if (command == "netinfo")
Debug_printWifiInfo();
else if (command == "formatCFG")
Debug_formatCFG();
else if (command == "formatPDS")
Debug_formatPersistence();
else if (command == "checkEE")
Debug_CheckEEPOM(false);
else if (command == "checkEEfix")
Debug_CheckEEPOM(true);
else if (command == "dumpEE1k")
dumpEEPROM(0, 1024);
else if (command == "dumpEE")
dumpEEPROM(0, EEPROM_SIZE_BYTES);
else if (command == "resetPageEE")
MovePersistencePage_EEPROM(true);
else if (command == "dumpCFG")
Debug_dumpConfig();
else if (command == "dumpPDS")
Debug_dumpPersistance();
else if (command == "saveEE")
globals.requestEEAction = EE_ALL_SAVE;
else if (command == "dumpGlobals")
Debug_dumpGlobals();
else if (command == "sdbg")
SetDebugportStatus(dbg_Serial, enabled);
else if (command == "dtc_show")
Debug_ShowDTCs();
else if (command == "dtc_clear")
ClearAllDTC();
else if (command == "dtc_crit")
MaintainDTC(DTC_FAKE_DTC_CRIT, true, millis());
else if (command == "dtc_warn")
MaintainDTC(DTC_FAKE_DTC_WARN, true, millis());
else if (command == "dtc_info")
MaintainDTC(DTC_FAKE_DTC_INFO, true, millis());
else if (command == "notify_error")
Websocket_PushNotification("Debug Error Notification", error);
else if (command == "notify_warning")
Websocket_PushNotification("Debug Warning Notification", warning);
else if (command == "notify_success")
Websocket_PushNotification("Debug Success Notification", success);
else if (command == "notify_info")
Websocket_PushNotification("Debug Info Notification", info);
else if (command == "purge")
Debug_Purge();
else if (command == "toggle_wifi")
globals.toggle_wifi = true;
std::vector<String> tokens;
size_t start = 0;
while (true)
{
int end = input.indexOf(' ', start);
if (end == -1) break;
tokens.push_back(input.substring(start, end));
start = static_cast<size_t>(end) + 1;
}
if (start < input.length())
tokens.push_back(input.substring(start));
return tokens;
}
// === getArg helper ===
String getArg(const std::vector<String> &args, size_t index, const String &defaultVal = "")
{
if (index < args.size())
return args[index];
return defaultVal;
}
// === Command Handler Map ===
typedef std::function<void(const String &args)> DebugCmdHandler;
static const std::map<String, DebugCmdHandler> &getCmdMap()
{
static const std::map<String, DebugCmdHandler> cmdMap = {
{"help", [](const String &)
{
Debug_log(LOG_INFO, "Available commands:\n");
for (const auto &entry : getCmdMap())
Debug_log(LOG_INFO, " - %s\n", entry.first.c_str());
}},
{"sysinfo", [](const String &)
{ Debug_printSystemInfo(); }},
{"netinfo", [](const String &)
{ Debug_printWifiInfo(); }},
{"formatCFG", [](const String &)
{ Debug_formatCFG(); }},
{"formatPDS", [](const String &)
{ Debug_formatPersistence(); }},
{"checkEE", [](const String &)
{ Debug_CheckEEPOM(false); }},
{"checkEEfix", [](const String &)
{ Debug_CheckEEPOM(true); }},
{"dumpEE1k", [](const String &)
{ dumpEEPROM(0, 1024); }},
{"dumpEE", [](const String &args)
{
int start = 0, len = EEPROM_SIZE_BYTES;
auto tokens = splitArgs(args);
if (tokens.size() >= 2)
{
start = tokens[0].toInt();
len = tokens[1].toInt();
}
dumpEEPROM(start, len);
}},
{"resetPageEE", [](const String &)
{ MovePersistencePage_EEPROM(true); }},
{"dumpCFG", [](const String &)
{ Debug_dumpConfig(); }},
{"dumpPDS", [](const String &)
{ Debug_dumpPersistance(); }},
{"saveEE", [](const String &)
{ globals.requestEEAction = EE_ALL_SAVE; }},
{"dumpGlobals", [](const String &)
{ Debug_dumpGlobals(); }},
{"sdbg", [](const String &)
{ SetDebugportStatus(dbg_Serial, enabled); }},
{"dtc_show", [](const String &)
{ Debug_ShowDTCs(); }},
{"dtc_clear", [](const String &)
{ ClearAllDTC(); }},
{"dtc_crit", [](const String &)
{ MaintainDTC(DTC_FAKE_DTC_CRIT, true, millis()); }},
{"dtc_warn", [](const String &)
{ MaintainDTC(DTC_FAKE_DTC_WARN, true, millis()); }},
{"dtc_info", [](const String &)
{ MaintainDTC(DTC_FAKE_DTC_INFO, true, millis()); }},
{"notify_error", [](const String &)
{ Websocket_PushNotification("Debug Error Notification", error); }},
{"notify_warning", [](const String &)
{ Websocket_PushNotification("Debug Warning Notification", warning); }},
{"notify_success", [](const String &)
{ Websocket_PushNotification("Debug Success Notification", success); }},
{"notify_info", [](const String &)
{ Websocket_PushNotification("Debug Info Notification", info); }},
{"purge", [](const String &)
{ Debug_Purge(); }},
{"toggle_wifi", [](const String &)
{ globals.toggle_wifi = true; }},
{"dtc_add", [](const String &args)
{
auto tokens = splitArgs(args);
if (!tokens.empty())
{
int code = tokens[0].toInt();
MaintainDTC((DTCNum_t)code, true, millis());
}
}},
{"tank_refill", [](const String &)
{ Debug_refillTank(); }},
{"isr_debug", [](const String &)
{
RegisterDebugPrintAuto(&globals.isr_debug, "isr_debug", 100, 20000);
}},
};
return cmdMap;
}
void processCmdDebug(String input)
{
input.trim();
int splitIndex = input.indexOf(' ');
String command = splitIndex == -1 ? input : input.substring(0, splitIndex);
String args = splitIndex == -1 ? "" : input.substring(splitIndex + 1);
auto &cmdMap = getCmdMap();
auto it = cmdMap.find(command);
if (it != cmdMap.end())
it->second(args);
else
Debug_pushMessage("unknown Command\n");
Debug_log(LOG_WARN, "Unknown command: '%s'\n", command.c_str());
}
/**
@@ -473,26 +573,6 @@ void Debug_ShowDTCs()
}
}
/**
* @brief Displays the help commands for debugging through Serial or WebUI.
* Each command is printed individually in a formatted manner.
*/
void Debug_printHelp()
{
char buff[64];
// Iterate through helpCmd and display each command
for (unsigned int i = 0; i < sizeof(helpCmd) / 63; i++)
{
// Copy a portion of helpCmd to buff for display
memcpy_P(buff, (helpCmd + (i * 63)), 63);
buff[63] = 0;
// Display the help command
Debug_pushMessage(buff);
}
}
/**
* @brief Start purging for 10 pulses.
*/
@@ -505,6 +585,13 @@ void Debug_Purge()
Debug_pushMessage("Purging 10 pulses\n");
}
void Debug_refillTank()
{
PersistenceData.tankRemain_microL = LubeConfig.tankCapacity_ml * 1000;
globals.requestEEAction = EE_PDS_SAVE;
Debug_pushMessage("Setting Tank to 100%\n");
}
/**
* @brief Convert a uint32_t value to a binary string with nibbles separated by a space.
*
@@ -533,3 +620,76 @@ const char *uint32_to_binary_string(uint32_t num)
binary_str[j] = '\0'; // Null terminator
return binary_str;
}
DebugStatus_t DebuggerStatus[dbg_cntElements];
struct DebugWatchEntry
{
const void *ptr;
String name;
uint32_t interval_ms;
uint32_t duration_ms;
uint32_t lastPrint_ms;
uint32_t start_ms;
std::function<void(const void*, const String&)> printer;
};
#define MAX_DEBUG_WATCHES 8
DebugWatchEntry debugWatches[MAX_DEBUG_WATCHES];
// === Typabhängige Druckfunktion ===
template<typename T>
void debugPrinterImpl(const void* ptr, const String& name) {
const T* typed = static_cast<const T*>(ptr);
if constexpr (std::is_same<T, bool>::value) {
Debug_pushMessage("%s = %s\n", name.c_str(), *typed ? "true" : "false");
} else if constexpr (std::is_floating_point<T>::value) {
Debug_pushMessage("%s = %.3f\n", name.c_str(), *typed);
} else if constexpr (std::is_signed<T>::value) {
Debug_pushMessage("%s = %ld\n", name.c_str(), static_cast<long>(*typed));
} else if constexpr (std::is_unsigned<T>::value) {
Debug_pushMessage("%s = %lu\n", name.c_str(), static_cast<unsigned long>(*typed));
}
}
// === Automatisches DebugPrint-Register ===
template<typename T>
void RegisterDebugPrintAuto(const T* ptr, const String& name, uint32_t interval_ms, uint32_t duration_ms)
{
for (int i = 0; i < MAX_DEBUG_WATCHES; ++i) {
if (debugWatches[i].ptr == nullptr) {
debugWatches[i] = {
ptr,
name,
interval_ms,
duration_ms,
0,
millis(),
debugPrinterImpl<T>
};
Debug_pushMessage("Registered Watch: %s\n", name.c_str());
return;
}
}
Debug_pushMessage("Debug Watch list full!\n");
}
// Debug-Ausgabe in Debug_Process():
void Debug_UpdateWatches() {
uint32_t now = millis();
for (int i = 0; i < MAX_DEBUG_WATCHES; ++i) {
auto& w = debugWatches[i];
if (!w.ptr) continue;
if (now - w.start_ms >= w.duration_ms) {
Debug_pushMessage("Watch expired: %s\n", w.name.c_str());
w.ptr = nullptr;
continue;
}
if (now - w.lastPrint_ms >= w.interval_ms) {
w.lastPrint_ms = now;
if (w.printer) w.printer(w.ptr, w.name);
}
}
}

131
Software/src/ledcontrol.cpp Normal file
View File

@@ -0,0 +1,131 @@
// === ledcontrol.cpp ===
#include "ledcontrol.h"
#include <Adafruit_NeoPixel.h>
#include "globals.h"
static Adafruit_NeoPixel leds(1, GPIO_LED, NEO_RGB + NEO_KHZ800);
static uint32_t basicColor = 0x000000;
static LedPattern basicPattern = LED_PATTERN_ON;
static uint32_t overrideColor = 0;
static LedPattern overridePattern = LED_PATTERN_ON;
static uint32_t overrideEndTime = 0;
static bool overrideActive = false;
void LEDControl_Init(uint8_t pin)
{
leds.begin();
leds.setBrightness(LubeConfig.LED_Max_Brightness);
leds.setPixelColor(0, 0);
leds.show();
}
void LEDControl_SetBasic(uint32_t color, LedPattern pattern)
{
basicColor = color;
basicPattern = pattern;
}
void LEDControl_SetOverride(uint32_t color, LedPattern pattern, uint32_t durationMs)
{
overrideColor = color;
overridePattern = pattern;
overrideEndTime = millis() + durationMs;
overrideActive = true;
if (durationMs == 0)
overrideEndTime = 0xFFFFFFFF; // Kein Timeout
}
void LEDControl_ClearOverride()
{
overrideActive = false;
overrideEndTime = 0;
}
void LEDControl_Update()
{
uint32_t now = millis();
uint32_t color = basicColor;
LedPattern pattern = basicPattern;
// Check override
if (overrideActive)
{
if (overrideEndTime != 0xFFFFFFFF && now >= overrideEndTime)
{
LEDControl_ClearOverride();
}
else
{
color = overrideColor;
pattern = overridePattern;
}
}
uint8_t brightness = LubeConfig.LED_Min_Brightness;
bool on = true;
switch (pattern)
{
case LED_PATTERN_ON:
brightness = LubeConfig.LED_Max_Brightness;
break;
case LED_PATTERN_FLASH:
on = (now % 1000) < 100;
brightness = LubeConfig.LED_Max_Brightness;
break;
case LED_PATTERN_FLASH_FAST:
on = (now % 500) < 50;
brightness = LubeConfig.LED_Max_Brightness;
break;
case LED_PATTERN_BLINK:
on = (now % 1000) < 500;
brightness = on ? LubeConfig.LED_Max_Brightness : 0;
break;
case LED_PATTERN_BLINK_FAST:
on = (now % 400) < 200;
brightness = on ? LubeConfig.LED_Max_Brightness : 0;
break;
case LED_PATTERN_BREATH:
{
uint32_t t = now % 2000;
if (t < 600)
{
// Schnell hochdimmen (600 ms)
brightness = map(t, 0, 600, LubeConfig.LED_Min_Brightness, LubeConfig.LED_Max_Brightness);
}
else
{
// Langsam runterdimmen (1400 ms)
brightness = map(t, 600, 2000, LubeConfig.LED_Max_Brightness, LubeConfig.LED_Min_Brightness);
}
break;
}
case LED_PATTERN_BREATH_REVERSE:
{
uint32_t t = now % 2000;
if (t < 1400)
{
// Langsam hochdimmen (1400 ms)
brightness = map(t, 0, 1400, LubeConfig.LED_Min_Brightness, LubeConfig.LED_Max_Brightness);
}
else
{
// Schnell runterdimmen (600 ms)
brightness = map(t, 1400, 2000, LubeConfig.LED_Max_Brightness, LubeConfig.LED_Min_Brightness);
}
break;
}
}
leds.setBrightness(brightness);
leds.setPixelColor(0, on ? color : 0);
leds.show();
}

View File

@@ -12,6 +12,7 @@
*/
#include "lubeapp.h"
#include "ledcontrol.h"
uint32_t lubePulseTimestamp = 0;
@@ -27,6 +28,9 @@ uint32_t lubePulseTimestamp = 0;
*/
void RunLubeApp(uint32_t add_milimeters)
{
static tSystem_Status lastSystemStatus = sysStat_Startup;
static uint16_t washModeRemainDistance = 0;
// Calculate and update tank percentage
globals.TankPercentage = PersistenceData.tankRemain_microL / (LubeConfig.tankCapacity_ml * 10);
@@ -42,24 +46,38 @@ void RunLubeApp(uint32_t add_milimeters)
if (PersistenceData.odometer_mm >= 1000000)
{
PersistenceData.odometer++;
PersistenceData.odometer_mm = 0;
PersistenceData.odometer_mm -= 1000000;
}
// Handle different system statuses
switch (globals.systemStatus)
{
case sysStat_Startup:
strcpy_P(globals.systemStatustxt, PSTR("Startup"));
if (lastSystemStatus != globals.systemStatus)
{
strcpy_P(globals.systemStatustxt, PSTR("Startup"));
LEDControl_SetBasic(LED_STARTUP_NORMAL, LED_PATTERN_BLINK);
lastSystemStatus = globals.systemStatus;
globals.resumeStatus = sysStat_Startup;
}
// Transition to Normal status after startup delay
if (millis() > STARTUP_DELAY)
{
globals.systemStatus = sysStat_Normal;
globals.resumeStatus = sysStat_Normal;
}
break;
case sysStat_Normal:
strcpy_P(globals.systemStatustxt, PSTR("Normal"));
if (lastSystemStatus != globals.systemStatus)
{
strcpy_P(globals.systemStatustxt, PSTR("Normal"));
LEDControl_SetBasic(LED_NORMAL_COLOR, LED_PATTERN_ON);
lastSystemStatus = globals.systemStatus;
globals.resumeStatus = sysStat_Normal;
}
// Trigger lube pulse if traveled distance exceeds the configured limit
if (PersistenceData.TravelDistance_highRes_mm / 1000 > LubeConfig.DistancePerLube_Default)
{
@@ -69,7 +87,14 @@ void RunLubeApp(uint32_t add_milimeters)
break;
case sysStat_Rain:
strcpy_P(globals.systemStatustxt, PSTR("Rain"));
if (lastSystemStatus != globals.systemStatus)
{
strcpy_P(globals.systemStatustxt, PSTR("Rain"));
LEDControl_SetBasic(LED_RAIN_COLOR, LED_PATTERN_ON);
lastSystemStatus = globals.systemStatus;
globals.resumeStatus = sysStat_Rain;
}
// Trigger lube pulse if traveled distance exceeds the configured limit in Rain mode
if (PersistenceData.TravelDistance_highRes_mm / 1000 > LubeConfig.DistancePerLube_Rain)
{
@@ -78,8 +103,42 @@ void RunLubeApp(uint32_t add_milimeters)
}
break;
case sysStat_Wash:
if (lastSystemStatus != globals.systemStatus)
{
washModeRemainDistance = LubeConfig.WashMode_Distance;
strcpy_P(globals.systemStatustxt, PSTR("Wash"));
LEDControl_SetBasic(LED_WASH_COLOR, LED_PATTERN_BREATH);
lastSystemStatus = globals.systemStatus;
}
// Trigger lube pulse if traveled distance exceeds the configured Interval in Wash mode
if (PersistenceData.TravelDistance_highRes_mm / 1000 > LubeConfig.WashMode_Interval)
{
LubePulse();
PersistenceData.TravelDistance_highRes_mm = 0;
if (washModeRemainDistance >= LubeConfig.WashMode_Interval)
{
washModeRemainDistance -= LubeConfig.WashMode_Interval;
Debug_pushMessage("Wash Distance remain: %d\n", washModeRemainDistance);
}
else
{
globals.systemStatus = globals.resumeStatus;
}
}
break;
case sysStat_Purge:
strcpy_P(globals.systemStatustxt, PSTR("Purge"));
if (lastSystemStatus != globals.systemStatus)
{
globals.purgePulses = LubeConfig.BleedingPulses;
strcpy_P(globals.systemStatustxt, PSTR("Purge"));
LEDControl_SetBasic(LED_PURGE_COLOR, LED_PATTERN_BLINK);
lastSystemStatus = globals.systemStatus;
}
// Execute lube pulses during the Purge status
if (globals.purgePulses > 0)
{
@@ -99,12 +158,26 @@ void RunLubeApp(uint32_t add_milimeters)
break;
case sysStat_Error:
strcpy_P(globals.systemStatustxt, PSTR("Error"));
if (lastSystemStatus != globals.systemStatus)
{
strcpy_P(globals.systemStatustxt, PSTR("Error"));
LEDControl_SetBasic(LED_ERROR_COLOR, LED_PATTERN_BLINK_FAST);
lastSystemStatus = globals.systemStatus;
}
globals.purgePulses = 0;
break;
case sysStat_Shutdown:
strcpy_P(globals.systemStatustxt, PSTR("Shutdown"));
if (lastSystemStatus != globals.systemStatus)
{
strcpy_P(globals.systemStatustxt, PSTR("Shutdown"));
LEDControl_SetBasic(LED_SHUTDOWN_COLOR, LED_PATTERN_BREATH_REVERSE);
lastSystemStatus = globals.systemStatus;
}
break;
default:

View File

@@ -39,6 +39,9 @@
#include "led_colors.h"
#include "obd2_kline.h"
#include "obd2_can.h"
#include "buttoncontrol.h"
#include "button_actions.h"
#include "ledcontrol.h"
#ifdef FEATURE_ENABLE_WIFI_CLIENT
#include <ESP8266WiFiMulti.h>
@@ -59,12 +62,10 @@ Adafruit_NeoPixel leds(1, GPIO_LED, NEO_RGB + NEO_KHZ800);
// Function-Prototypes
void IRAM_ATTR trigger_ISR();
void LED_Process(uint8_t override = false, uint32_t setColor = LED_DEFAULT_COLOR);
#ifdef FEATURE_ENABLE_OLED
U8X8_SSD1306_128X64_NONAME_HW_I2C u8x8(-1);
void Display_Process();
#endif
void Button_Process();
void toggleWiFiAP(bool shutdown = false);
void SystemShutdown(bool restart = false);
uint32_t Process_Impulse_WheelSpeed();
@@ -134,7 +135,7 @@ void setup()
Serial.print("\nEE-Init done");
// Initialize LEDs
leds.begin();
LEDControl_Init(GPIO_LED);
Serial.print("\nLED-Init done");
// Initialize based on the chosen speed source (CAN, GPS, Impulse)
@@ -175,6 +176,8 @@ void setup()
pinMode(GPIO_BUTTON, INPUT_PULLUP);
pinMode(GPIO_PUMP, OUTPUT);
ButtonControl_Init(GPIO_BUTTON, buttonActions, buttonActionCount);
// Set up OTA updates
ArduinoOTA.setPort(8266);
ArduinoOTA.setHostname(globals.DeviceName);
@@ -249,14 +252,15 @@ void loop()
// Process button input, manage LED behavior, perform EEPROM tasks, handle webserver operations,
// process Diagnostic Trouble Codes (DTC), and manage debugging
Button_Process();
LED_Process();
ButtonControl_Update();
LEDControl_Update();
EEPROM_Process();
Webserver_Process();
DTC_Process();
Debug_Process();
if (globals.toggle_wifi == true){
if (globals.toggle_wifi == true)
{
globals.toggle_wifi = false;
toggleWiFiAP();
@@ -335,214 +339,19 @@ void EEPROMCyclicPDS_callback()
* This ISR is called whenever a pulse is detected from the wheel speed sensor. It increments
* the `wheel_pulse` variable, which is used to track the number of pulses received.
*/
void trigger_ISR()
volatile uint32_t lastTriggerMicros = 0;
void IRAM_ATTR trigger_ISR()
{
uint32_t now = micros();
if (now - lastTriggerMicros < 2500)
return;
lastTriggerMicros = now;
globals.isr_debug++;
wheel_pulse++;
}
/**
* @brief Manages LED behavior based on the current system status and user overrides.
*
* This function handles LED behavior, including startup animations, confirmation animations for
* normal and rain modes, indication for purge, error, shutdown, and normal operation. It supports
* user overrides to set a specific LED color. The LED status is determined by the current system
* status, and specific LED patterns are displayed accordingly.
*
* @param override Flag indicating whether to override the LED behavior (0: No override, 1: Override, 2: Resume previous state).
* @param SetColor The color to set when overriding the LED behavior.
*/
void LED_Process(uint8_t override, uint32_t SetColor)
{
// Enumeration to represent LED status
typedef enum
{
LED_Startup,
LED_Normal,
LED_Confirm_Normal,
LED_Rain,
LED_Confirm_Rain,
LED_Purge,
LED_Error,
LED_Shutdown,
LED_Override
} tLED_Status;
// Static variables to track LED status, system status, override color, and previous LED status
static tSystem_Status oldSysStatus = sysStat_Startup;
static tLED_Status LED_Status = LED_Startup;
static uint32_t LED_override_color = 0;
static tLED_Status LED_ResumeOverrideStatus = LED_Startup;
// Variables for managing LED animation timing
uint8_t color = 0;
uint32_t timer = 0;
uint32_t animtimer = 0;
static uint32_t timestamp = 0;
timer = millis();
// Handle LED overrides
if (override == 1)
{
if (LED_Status != LED_Override)
{
LED_ResumeOverrideStatus = LED_Status;
Debug_pushMessage("Override LED_Status\n");
}
LED_Status = LED_Override;
LED_override_color = SetColor;
}
if (override == 2)
{
if (LED_Status == LED_Override)
{
LED_Status = LED_ResumeOverrideStatus;
Debug_pushMessage("Resume LED_Status\n");
}
}
// Update LED status when system status changes
if (oldSysStatus != globals.systemStatus)
{
switch (globals.systemStatus)
{
case sysStat_Startup:
LED_Status = LED_Startup;
Debug_pushMessage("sysStat: Startup\n");
break;
case sysStat_Normal:
timestamp = timer + 3500;
LED_Status = LED_Confirm_Normal;
Debug_pushMessage("sysStat: Normal\n");
break;
case sysStat_Rain:
timestamp = timer + 3500;
LED_Status = LED_Confirm_Rain;
Debug_pushMessage("sysStat: Rain\n");
break;
case sysStat_Purge:
LED_Status = LED_Purge;
Debug_pushMessage("sysStat: Purge\n");
break;
case sysStat_Error:
LED_Status = LED_Error;
Debug_pushMessage("sysStat: Error\n");
break;
case sysStat_Shutdown:
LED_Status = LED_Shutdown;
Debug_pushMessage("sysStat: Shutdown\n");
break;
default:
break;
}
oldSysStatus = globals.systemStatus;
}
// Handle different LED statuses
switch (LED_Status)
{
case LED_Startup:
leds.setBrightness(LubeConfig.LED_Max_Brightness);
if (globals.TankPercentage < LubeConfig.TankRemindAtPercentage)
leds.setPixelColor(0, LED_STARTUP_TANKWARN);
else
leds.setPixelColor(0, LED_STARTUP_NORMAL);
break;
case LED_Confirm_Normal:
animtimer = timer % 500;
color = map(animtimer / 2, 0, 250, 0, LubeConfig.LED_Max_Brightness);
leds.setPixelColor(0, LED_NORMAL_COLOR);
if (animtimer < 250)
leds.setBrightness(color);
else
leds.setBrightness(LubeConfig.LED_Max_Brightness - color);
if (timestamp < timer)
{
LED_Status = LED_Normal;
Debug_pushMessage("LED_Status: Confirm -> Normal\n");
}
break;
case LED_Normal:
leds.setBrightness(LubeConfig.LED_Min_Brightness);
leds.setPixelColor(0, LED_NORMAL_COLOR);
if (timer % 2000 > 1950 && LubeConfig.LED_Mode_Flash == true)
leds.setBrightness(LubeConfig.LED_Max_Brightness);
else if (timer % 2000 > 1500 && WiFi.getMode() != WIFI_OFF)
leds.setPixelColor(0, LED_WIFI_BLINK);
break;
case LED_Confirm_Rain:
animtimer = timer % 500;
color = map(animtimer / 2, 0, 250, 0, LubeConfig.LED_Max_Brightness);
leds.setPixelColor(0, LED_RAIN_COLOR);
if (animtimer < 250)
leds.setBrightness(color);
else
leds.setBrightness(LubeConfig.LED_Max_Brightness - color);
if (timestamp < timer)
{
LED_Status = LED_Rain;
Debug_pushMessage("LED_Status: Confirm -> Rain\n");
}
break;
case LED_Rain:
leds.setBrightness(LubeConfig.LED_Min_Brightness);
leds.setPixelColor(0, LED_RAIN_COLOR);
if (timer % 2000 > 1950 && LubeConfig.LED_Mode_Flash == true)
leds.setBrightness(LubeConfig.LED_Max_Brightness);
else if (timer % 2000 > 1500 && WiFi.getMode() != WIFI_OFF)
leds.setPixelColor(0, LED_WIFI_BLINK);
break;
case LED_Purge:
timer = timer % 500;
color = map(timer / 2, 0, 250, LubeConfig.LED_Min_Brightness, LubeConfig.LED_Max_Brightness);
leds.setPixelColor(0, LED_PURGE_COLOR);
if (timer < 250)
leds.setBrightness(color);
else
leds.setBrightness(LubeConfig.LED_Max_Brightness - color);
break;
case LED_Error:
leds.setBrightness(LubeConfig.LED_Max_Brightness);
leds.setPixelColor(0, timer % 500 > 250 ? LED_ERROR_BLINK : 0);
break;
case LED_Shutdown:
timer = timer % 600;
leds.setPixelColor(0, LED_SHUTDOWN_BLINK);
if (timer < 500)
{
color = map(timer, 0, 500, LubeConfig.LED_Max_Brightness, LubeConfig.LED_Min_Brightness);
leds.setBrightness(color);
}
else
{
leds.setBrightness(LubeConfig.LED_Min_Brightness);
}
break;
case LED_Override:
leds.setBrightness(LubeConfig.LED_Max_Brightness);
leds.setPixelColor(0, LED_override_color);
break;
default:
break;
}
leds.show();
}
#ifdef FEATURE_ENABLE_OLED
/**
* @brief Manages the display content based on the current system status and updates the OLED display.
@@ -570,7 +379,22 @@ void Display_Process()
u8x8.setCursor(0, 1);
// Calculate remaining lubrication distance based on system mode
uint32_t DistRemain = globals.systemStatus == sysStat_Normal ? LubeConfig.DistancePerLube_Default : LubeConfig.DistancePerLube_Rain;
uint32_t DistRemain = 0;
switch (globals.systemStatus)
{
case sysStat_Normal:
DistRemain = LubeConfig.DistancePerLube_Default;
break;
case sysStat_Rain:
DistRemain = LubeConfig.DistancePerLube_Rain;
break;
case sysStat_Wash:
DistRemain = LubeConfig.WashMode_Interval;
break;
default:
DistRemain = 0;
break;
}
DistRemain = DistRemain - (PersistenceData.TravelDistance_highRes_mm / 1000);
// Display relevant information on the OLED screen based on system status
@@ -597,119 +421,6 @@ void Display_Process()
}
#endif
/**
* @brief Processes the button input and performs corresponding actions based on button state and timing.
*
* This function handles the button input, detecting button presses and executing actions based on
* predefined time delays. Actions include toggling WiFi, starting purge, toggling operating modes,
* and displaying feedback through LEDs. The function utilizes an enumeration to track button actions
* and manages the timing for different actions.
*/
void Button_Process()
{
// Time delays for different button actions
#define BUTTON_ACTION_DELAY_TOGGLEMODE 500
#define BUTTON_ACTION_DELAY_PURGE 3500
#define BUTTON_ACTION_DELAY_WIFI 6500
#define BUTTON_ACTION_DELAY_NOTHING 9500
// Enumeration to represent button actions
typedef enum buttonAction_e
{
BTN_INACTIVE,
BTN_NOTHING,
BTN_TOGGLEMODE,
BTN_TOGGLEWIFI,
BTN_STARTPURGE
} buttonAction_t;
// Static variables to track button state and timing
static uint32_t buttonTimestamp = 0;
static buttonAction_t buttonAction = BTN_INACTIVE;
// Check if button is pressed (LOW)
if (digitalRead(GPIO_BUTTON) == LOW)
{
// Update button timestamp on the first button press
if (buttonTimestamp == 0)
buttonTimestamp = millis();
// Check and execute actions based on predefined time delays
if (buttonTimestamp + BUTTON_ACTION_DELAY_NOTHING < millis())
{
LED_Process(1, COLOR_WARM_WHITE);
buttonAction = BTN_NOTHING;
}
else if (buttonTimestamp + BUTTON_ACTION_DELAY_WIFI < millis())
{
LED_Process(1, LED_WIFI_BLINK);
buttonAction = BTN_TOGGLEWIFI;
}
else if (buttonTimestamp + BUTTON_ACTION_DELAY_PURGE < millis())
{
LED_Process(1, LED_PURGE_COLOR);
buttonAction = BTN_STARTPURGE;
}
else if (buttonTimestamp + BUTTON_ACTION_DELAY_TOGGLEMODE < millis())
{
uint32_t color = globals.systemStatus == sysStat_Normal ? LED_RAIN_COLOR : LED_NORMAL_COLOR;
LED_Process(1, color);
buttonAction = BTN_TOGGLEMODE;
}
}
else // Button is released
{
// Execute corresponding actions based on the detected button action
if (buttonAction != BTN_INACTIVE)
{
switch (buttonAction)
{
case BTN_TOGGLEWIFI:
toggleWiFiAP();
Debug_pushMessage("Starting WiFi AP\n");
break;
case BTN_STARTPURGE:
globals.systemStatus = sysStat_Purge;
globals.purgePulses = LubeConfig.BleedingPulses;
Debug_pushMessage("Starting Purge\n");
break;
case BTN_TOGGLEMODE:
switch (globals.systemStatus)
{
case sysStat_Normal:
globals.systemStatus = sysStat_Rain;
globals.resumeStatus = sysStat_Rain;
break;
case sysStat_Rain:
globals.systemStatus = sysStat_Normal;
globals.resumeStatus = sysStat_Normal;
break;
default:
break;
}
Debug_pushMessage("Toggling Mode\n");
break;
case BTN_NOTHING:
default:
Debug_pushMessage("Nothing or invalid\n");
break;
}
// Display feedback through LEDs
LED_Process(2);
}
// Reset button state and timestamp
buttonAction = BTN_INACTIVE;
buttonTimestamp = 0;
}
}
/**
* @brief Toggles the WiFi functionality based on the current status.
*
@@ -722,6 +433,8 @@ void Button_Process()
*/
void toggleWiFiAP(bool shutdown)
{
LEDControl_SetOverride(LED_WIFI_COLOR, LED_PATTERN_BLINK_FAST, 2500);
// Check if WiFi is currently active
if (WiFi.getMode() != WIFI_OFF)
{

View File

@@ -3,10 +3,10 @@
*
* @brief Implementation file for converting structs to JSON objects.
*
* @note This file is auto-generated by a script on 2024-01-30 20:29:34.
* @note This file is auto-generated by a script on 2025-06-15 11:37:51.
*
* @author Marcel Peterkau
* @date 30.01.2024
* @date 15.06.2025
*/
@@ -26,6 +26,8 @@ void generateJsonObject_LubeConfig(JsonObject data)
data["RimDiameter_Inch"] = LubeConfig.RimDiameter_Inch;
data["DistancePerRevolution_mm"] = LubeConfig.DistancePerRevolution_mm;
data["BleedingPulses"] = LubeConfig.BleedingPulses;
data["WashMode_Distance"] = LubeConfig.WashMode_Distance;
data["WashMode_Interval"] = LubeConfig.WashMode_Interval;
data["SpeedSource"] = LubeConfig.SpeedSource;
data["GPSBaudRate"] = LubeConfig.GPSBaudRate;
data["CANSource"] = LubeConfig.CANSource;
@@ -52,4 +54,4 @@ void generateJsonObject_PersistenceData(JsonObject data)
// CODEGENERATOR_CHECKSUM: 59f35aadffd0bbef253210ea2fbaaf9a515553a2e3cc9bf4cfa2819b63c969ce
// CODEGENERATOR_CHECKSUM: 4702cb49ea55617cbb34715164810bb58d3c3f46fb1653b6f47bd4fd9cb0031e

View File

@@ -12,6 +12,10 @@
*/
#include "webui.h"
#include "common.h"
#include <memory> // std::unique_ptr
#include <cstring> // strlen, strncpy, memcpy
#include <algorithm> // std::clamp
AsyncWebServer webServer(80);
@@ -19,6 +23,28 @@ const char *PARAM_MESSAGE = "message";
SpeedSource_t speedsourcePreselect; /**< Preselect Memory for change SourceAdress */
struct WsInitBurst
{
uint32_t client_id = 0;
uint8_t step = 0; // 0..N
uint32_t next_due_ms = 0;
bool active = false;
} g_wsBurst;
static const char kMappingStatus[] =
"MAPPING_STATUS:systemstatus;tankremain;odometer;";
static const char kMappingStatic[] =
"MAPPING_STATIC:"
"lubedistancenormal;lubedistancerain;washdistance;washinterval;"
"tankcap;pumppulse;tankwarn;pulserev;tirewidth;tireratio;tiredia;"
"speedsource;speedsource-options;"
"gpsbaud;gpsbaud-options;"
"cansource;cansource-options;"
"ledmodeflash;ledmaxbrightness;ledminbrightness;"
"showimpulse;showgps;showcan;bleedingpulses;wifi-ssid;wifi-password;"
"fw-version;req-flash-version;git-rev;flash-version";
String processor(const String &var);
void WebserverNotFound_Callback(AsyncWebServerRequest *request);
void WebserverFirmwareUpdate_Callback(AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final);
@@ -38,6 +64,34 @@ void Websocket_HandleSettings(uint8_t *data);
void parseWebsocketString(char *data, char *identifierBuffer, size_t identifierBufferSize, char *valueBuffer, size_t valueBufferSize);
int findIndexByString(const char *searchString, const char *const *array, int arraySize);
// ---------- small helpers (safety) ----------
static inline const char *nz(const char *p) { return p ? p : ""; }
static inline String tableStr(const char *const *tbl, int idx, int size)
{
if (idx < 0 || idx >= size)
return String();
const char *p = tbl[idx];
return p ? String(p) : String();
}
static void appendCsv(String &out, const char *const *arr, size_t n)
{
for (size_t i = 0; i < n; ++i)
{
if (!arr[i])
continue;
out += arr[i];
if (i + 1 < n)
out += ",";
}
}
static inline bool validIndex(int idx, int size)
{
return idx >= 0 && idx < size;
}
/**
* @brief Initializes the web-based user interface (WebUI) for the ChainLube application.
*
@@ -116,6 +170,54 @@ void Webserver_Process()
Websocket_RefreshClientData_Status(0);
previousMillis = millis();
}
// Gestaffelter Initial-Burst nach Verbindungsaufbau
if (g_wsBurst.active && millis() >= g_wsBurst.next_due_ms)
{
if (!webSocket.hasClient(g_wsBurst.client_id))
{
g_wsBurst.active = false; // Client ist schon wieder weg
}
else if (!webSocket.availableForWrite(g_wsBurst.client_id))
{
g_wsBurst.next_due_ms = millis() + 10; // kurz warten, Puffer voll
}
else
{
switch (g_wsBurst.step)
{
case 0:
// Mapping Status
webSocket.text(g_wsBurst.client_id, kMappingStatus);
g_wsBurst.step++;
g_wsBurst.next_due_ms = millis() + 25;
break;
case 1:
// Status-Daten (send_mapping=false!)
Websocket_RefreshClientData_Status(g_wsBurst.client_id, false);
g_wsBurst.step++;
g_wsBurst.next_due_ms = millis() + 25;
break;
case 2:
// Mapping Static (achte auf 'wifi-password')
webSocket.text(g_wsBurst.client_id, kMappingStatic);
g_wsBurst.step++;
g_wsBurst.next_due_ms = millis() + 25;
break;
case 3:
// Static-Daten (send_mapping=false!)
Websocket_RefreshClientData_Static(g_wsBurst.client_id, false);
g_wsBurst.step++;
[[fallthrough]];
default:
g_wsBurst.active = false;
break;
}
}
}
}
/**
@@ -165,14 +267,15 @@ void GetFlashVersion(char *buff, size_t buff_size)
{
File this_file = LittleFS.open("version", "r");
if (!this_file)
{ // failed to open the file, retrn empty result
{ // failed to open the file, return empty result
buff[0] = '\0';
return;
}
if (this_file.available())
{
int bytes_read;
bytes_read = this_file.readBytesUntil('\r', buff, buff_size - 1);
int bytes_read = this_file.readBytesUntil('\r', buff, buff_size - 1);
if (bytes_read < 0)
bytes_read = 0;
buff[bytes_read] = '\0';
}
this_file.close();
@@ -270,7 +373,7 @@ void WebserverEERestore_Callback(AsyncWebServerRequest *request, const String &f
}
}
if (buffer != NULL)
if (buffer != NULL && len > 0)
{
memcpy(buffer + read_ptr, data, len);
read_ptr = read_ptr + len;
@@ -280,6 +383,11 @@ void WebserverEERestore_Callback(AsyncWebServerRequest *request, const String &f
{
if (buffer != NULL)
{
// Ensure zero-termination just in case
if (read_ptr >= 1536)
read_ptr = 1535;
buffer[read_ptr] = '\0';
Serial.print(buffer);
JsonDocument json;
error = deserializeJson(json, buffer);
@@ -323,7 +431,11 @@ void WebserverEERestore_Callback(AsyncWebServerRequest *request, const String &f
}
}
free(buffer);
if (buffer)
{
free(buffer);
buffer = NULL;
}
AsyncWebServerResponse *response = request->beginResponse(302, "text/plain", "Please wait while the device reboots");
response->addHeader("Refresh", "20");
@@ -354,10 +466,10 @@ void WebServerEEJSON_Callback(AsyncWebServerRequest *request)
char buffer[16];
info["DeviceName"] = globals.DeviceName;
info["DeviceName"] = nz(globals.DeviceName);
sprintf(buffer, "%d.%02d", constants.Required_Flash_Version_major, constants.Required_Flash_Version_minor);
info["FW-Version"] = buffer;
info["FS-Version"] = globals.FlashVersion;
info["FS-Version"] = nz(globals.FlashVersion);
snprintf_P(buffer, sizeof(buffer), "%s", constants.GitHash);
info["Git-Hash"] = buffer;
@@ -395,11 +507,16 @@ void WebsocketEvent_Callback(AsyncWebSocket *server, AsyncWebSocketClient *clien
switch (type)
{
case WS_EVT_CONNECT:
Debug_pushMessage("WebSocket client #%u connected from %s\n", client->id(), client->remoteIP().toString().c_str());
Websocket_RefreshClientData_Status(client->id(), true);
Websocket_RefreshClientData_Static(client->id(), true);
Websocket_RefreshClientData_DTCs(client->id());
{
Debug_pushMessage("WebSocket client #%u connected from %s\n",
client->id(), client->remoteIP().toString().c_str());
// NICHT direkt senden! Nur Burst triggern:
g_wsBurst.client_id = client->id();
g_wsBurst.step = 0;
g_wsBurst.next_due_ms = millis(); // sofort startbereit
g_wsBurst.active = true;
break;
}
case WS_EVT_DISCONNECT:
Debug_pushMessage("WebSocket client #%u disconnected\n", client->id());
break;
@@ -427,20 +544,24 @@ void Websocket_HandleMessage(void *arg, uint8_t *data, size_t len)
AwsFrameInfo *info = (AwsFrameInfo *)arg;
if (info->final && info->index == 0 && info->len == len && info->opcode == WS_TEXT)
{
data[len] = 0;
Debug_pushMessage("Websocket-Message (len: %d): %s\n", len, (char *)data);
// Create a safe, null-terminated local copy
std::unique_ptr<char[]> buf(new char[len + 1]);
memcpy(buf.get(), data, len);
buf[len] = '\0';
if (strncmp((char *)data, "btn-", strlen("btn-")) == 0)
Debug_pushMessage("Websocket-Message (len: %d): %s\n", (int)len, buf.get());
if (strncmp(buf.get(), "btn-", 4) == 0)
{
Websocket_HandleButtons(data + strlen("btn-"));
Websocket_HandleButtons((uint8_t *)buf.get() + 4);
}
else if (strncmp((char *)data, "set-", strlen("set-")) == 0)
else if (strncmp(buf.get(), "set-", 4) == 0)
{
Websocket_HandleSettings(data + strlen("set-"));
Websocket_HandleSettings((uint8_t *)buf.get() + 4);
}
else
{
Debug_pushMessage("Got unknown Websocket-Message '%s' from client\n", (char *)data);
Debug_pushMessage("Got unknown Websocket-Message '%s' from client\n", buf.get());
}
}
}
@@ -480,7 +601,6 @@ void Websocket_HandleButtons(uint8_t *data)
else if (strcmp(identifier, "purgenow") == 0)
{
globals.systemStatus = sysStat_Purge;
globals.purgePulses = LubeConfig.BleedingPulses;
}
else if (strcmp(identifier, "sourcesave") == 0)
{
@@ -499,6 +619,7 @@ void Websocket_HandleButtons(uint8_t *data)
else if (strcmp(identifier, "resettank") == 0)
{
PersistenceData.tankRemain_microL = LubeConfig.tankCapacity_ml * 1000;
globals.requestEEAction = EE_PDS_SAVE;
}
else
{
@@ -527,18 +648,27 @@ void Websocket_HandleSettings(uint8_t *data)
}
else if (strcmp(identifier, "speedsource") == 0)
{
int index = findIndexByString(value, SpeedSourceString, SpeedSourceString_Elements);
speedsourcePreselect = (SpeedSource_t)index;
int index = findIndexByString(value, SpeedSourceString, (int)SpeedSourceString_Elements);
if (validIndex(index, (int)SpeedSourceString_Elements))
speedsourcePreselect = (SpeedSource_t)index;
else
Debug_pushMessage("Invalid speedsource '%s'\n", value);
}
else if (strcmp(identifier, "cansource") == 0)
{
int index = findIndexByString(value, CANSourceString, CANSourceString_Elements);
LubeConfig.CANSource = (CANSource_t)index;
int index = findIndexByString(value, CANSourceString, (int)CANSourceString_Elements);
if (validIndex(index, (int)CANSourceString_Elements))
LubeConfig.CANSource = (CANSource_t)index;
else
Debug_pushMessage("Invalid cansource '%s'\n", value);
}
else if (strcmp(identifier, "gpsbaud") == 0)
{
int index = findIndexByString(value, GPSBaudRateString, GPSBaudRateString_Elements);
LubeConfig.GPSBaudRate = (GPSBaudRate_t)index;
int index = findIndexByString(value, GPSBaudRateString, (int)GPSBaudRateString_Elements);
if (validIndex(index, (int)GPSBaudRateString_Elements))
LubeConfig.GPSBaudRate = (GPSBaudRate_t)index;
else
Debug_pushMessage("Invalid gpsbaud '%s'\n", value);
}
else if (strcmp(identifier, "ledmaxbrightness") == 0)
{
@@ -570,7 +700,7 @@ void Websocket_HandleSettings(uint8_t *data)
}
else if (strcmp(identifier, "ledmodeflash") == 0)
{
LubeConfig.LED_Mode_Flash = value[0] == '1' ? true : false;
LubeConfig.LED_Mode_Flash = value[0] == '1';
}
else if (strcmp(identifier, "wifi-ssid") == 0)
{
@@ -580,6 +710,14 @@ void Websocket_HandleSettings(uint8_t *data)
{
strncpy(LubeConfig.wifi_client_password, value, sizeof(LubeConfig.wifi_client_password));
}
else if (strcmp(identifier, "washinterval") == 0)
{
LubeConfig.WashMode_Interval = atoi(value);
}
else if (strcmp(identifier, "washdistance") == 0)
{
LubeConfig.WashMode_Distance = atoi(value);
}
else
{
Debug_pushMessage("Got unknown Settings-id and value '%s' from ws-client\n", identifier);
@@ -655,21 +793,22 @@ void Websocket_RefreshClientData_Status(uint32_t client_id, bool send_mapping)
if (send_mapping)
{
const char mapping[] = "MAPPING_STATUS:"
"systemstatus;"
"tankremain;"
"odometer;";
if (client_id > 0)
webSocket.text(client_id, mapping);
webSocket.text(client_id, kMappingStatus);
else
webSocket.textAll(mapping);
webSocket.textAll(kMappingStatus);
}
String temp = "STATUS:";
temp.concat(String(globals.systemStatustxt) + ";");
temp.concat(String((PersistenceData.tankRemain_microL / 10) / LubeConfig.tankCapacity_ml) + ";");
temp.concat(String(nz(globals.systemStatustxt)) + ";");
// Guard against division by zero (capacity==0)
uint32_t cap = LubeConfig.tankCapacity_ml;
uint32_t remain10 = (PersistenceData.tankRemain_microL / 10); // keep your original math
uint32_t ratio = (cap > 0) ? (remain10 / cap) : 0;
temp.concat(String(ratio) + ";");
temp.concat(String(PersistenceData.odometer + (PersistenceData.odometer_mm / 1000)) + ";");
if (client_id > 0)
@@ -694,76 +833,76 @@ void Websocket_RefreshClientData_Status(uint32_t client_id, bool send_mapping)
*/
void Websocket_RefreshClientData_Static(uint32_t client_id, bool send_mapping)
{
if (send_mapping)
{
const char mapping[] = "MAPPING_STATIC:"
"lubedistancenormal;"
"lubedistancerain;"
"tankcap;"
"pumppulse;"
"tankwarn;"
"pulserev;"
"tirewidth;"
"tireratio;"
"tiredia;"
"speedsource;"
"gpsbaud;"
"cansource;"
"ledmodeflash;"
"ledmaxbrightness;"
"ledminbrightness;"
"showimpulse;"
"showgps;"
"showcan;"
"bleedingpulses;"
"wifi-ssid;"
"wifi-pass;";
if (client_id > 0)
webSocket.text(client_id, mapping);
webSocket.text(client_id, kMappingStatic);
else
webSocket.textAll(mapping);
webSocket.textAll(kMappingStatic);
}
String temp = "STATIC:";
temp.concat(String(LubeConfig.DistancePerLube_Default) + ";");
temp.concat(String(LubeConfig.DistancePerLube_Rain) + ";");
temp.concat(String(LubeConfig.tankCapacity_ml) + ";");
temp.concat(String(LubeConfig.amountPerDose_microL) + ";");
temp.concat(String(LubeConfig.TankRemindAtPercentage) + ";");
temp.concat(String(LubeConfig.PulsePerRevolution) + ";");
temp.concat(String(LubeConfig.TireWidth_mm) + ";");
temp.concat(String(LubeConfig.TireWidthHeight_Ratio) + ";");
temp.concat(String(LubeConfig.RimDiameter_Inch) + ";");
temp.concat(String(SpeedSourceString[LubeConfig.SpeedSource]) + ";");
temp.concat(String(GPSBaudRateString[LubeConfig.GPSBaudRate]) + ";");
temp.concat(String(CANSourceString[LubeConfig.CANSource]) + ";");
temp.concat(String(LubeConfig.LED_Mode_Flash == true ? "1" : "0") + ";");
temp.concat(String(LubeConfig.LED_Max_Brightness) + ";");
temp.concat(String(LubeConfig.LED_Min_Brightness) + ";");
temp.concat(String(LubeConfig.SpeedSource == SOURCE_IMPULSE ? "1" : "0") + ";");
temp.concat(String(LubeConfig.SpeedSource == SOURCE_GPS ? "1" : "0") + ";");
temp.concat(String(LubeConfig.SpeedSource == SOURCE_CAN ? "1" : "0") + ";");
temp.concat(String(LubeConfig.BleedingPulses) + ";");
temp.concat(String(LubeConfig.wifi_client_ssid) + ";");
temp.concat(String(LubeConfig.wifi_client_password) + ";");
temp += String(LubeConfig.DistancePerLube_Default) + ";";
temp += String(LubeConfig.DistancePerLube_Rain) + ";";
temp += String(LubeConfig.WashMode_Distance) + ";";
temp += String(LubeConfig.WashMode_Interval) + ";";
temp += String(LubeConfig.tankCapacity_ml) + ";";
temp += String(LubeConfig.amountPerDose_microL) + ";";
temp += String(LubeConfig.TankRemindAtPercentage) + ";";
temp += String(LubeConfig.PulsePerRevolution) + ";";
temp += String(LubeConfig.TireWidth_mm) + ";";
temp += String(LubeConfig.TireWidthHeight_Ratio) + ";";
temp += String(LubeConfig.RimDiameter_Inch) + ";";
for (uint32_t i = 0; i < SpeedSourceString_Elements; i++)
// speedsource + Optionen
temp += tableStr(SpeedSourceString, (int)LubeConfig.SpeedSource, (int)SpeedSourceString_Elements) + ";";
{
temp.concat(String(SpeedSourceString[i]) + ",");
String csv;
appendCsv(csv, SpeedSourceString, SpeedSourceString_Elements);
temp += csv + ";";
}
temp.concat(";");
// gpsbaud + Optionen
temp += tableStr(GPSBaudRateString, (int)LubeConfig.GPSBaudRate, (int)GPSBaudRateString_Elements) + ";";
{
String csv;
appendCsv(csv, GPSBaudRateString, GPSBaudRateString_Elements);
temp += csv + ";";
}
// cansource + Optionen
temp += tableStr(CANSourceString, (int)LubeConfig.CANSource, (int)CANSourceString_Elements) + ";";
{
String csv;
appendCsv(csv, CANSourceString, CANSourceString_Elements);
temp += csv + ";";
}
temp += (LubeConfig.LED_Mode_Flash ? "1" : "0");
temp += ";";
temp += String(LubeConfig.LED_Max_Brightness) + ";";
temp += String(LubeConfig.LED_Min_Brightness) + ";";
temp += String(LubeConfig.SpeedSource == SOURCE_IMPULSE ? 1 : 0) + ";";
temp += String(LubeConfig.SpeedSource == SOURCE_GPS ? 1 : 0) + ";";
temp += String(LubeConfig.SpeedSource == SOURCE_CAN ? 1 : 0) + ";";
temp += String(LubeConfig.BleedingPulses) + ";";
temp += String(nz(LubeConfig.wifi_client_ssid)) + ";";
temp += String(nz(LubeConfig.wifi_client_password)) + ";";
// Versionen (x.XX)
char ver_fw[8], ver_reqfs[8];
snprintf(ver_fw, sizeof(ver_fw), "%u.%02u", constants.FW_Version_major, constants.FW_Version_minor);
snprintf(ver_reqfs, sizeof(ver_reqfs), "%u.%02u", constants.Required_Flash_Version_major, constants.Required_Flash_Version_minor);
temp += String(ver_fw) + ";";
temp += String(ver_reqfs) + ";";
temp += String(nz(constants.GitHash)) + ";";
temp += String(nz(globals.FlashVersion)) + ";";
if (client_id > 0)
{
webSocket.text(client_id, temp);
}
else
{
webSocket.textAll(temp);
}
}
/**
@@ -791,7 +930,7 @@ void parseWebsocketString(char *data, char *identifierBuffer, size_t identifierB
{
// Kopieren des ersten Teils in den Buffer für Identifier
strncpy(identifierBuffer, token, identifierBufferSize - 1);
identifierBuffer[identifierBufferSize - 1] = '\0'; // Null-Terminierung sicherstellen
identifierBuffer[identifierBufferSize - 1] = '\0';
// Weitere Aufrufe von strtok, um den nächsten Teil zu erhalten
token = strtok(NULL, ":");
@@ -801,7 +940,7 @@ void parseWebsocketString(char *data, char *identifierBuffer, size_t identifierB
{
// Kopieren des zweiten Teils in den Buffer für Value
strncpy(valueBuffer, token, valueBufferSize - 1);
valueBuffer[valueBufferSize - 1] = '\0'; // Null-Terminierung sicherstellen
valueBuffer[valueBufferSize - 1] = '\0';
}
else
{
@@ -816,7 +955,7 @@ void parseWebsocketString(char *data, char *identifierBuffer, size_t identifierB
// Der gesamte String wird als Value betrachtet
strncpy(valueBuffer, data, valueBufferSize - 1);
valueBuffer[valueBufferSize - 1] = '\0'; // Null-Terminierung sicherstellen
valueBuffer[valueBufferSize - 1] = '\0';
}
}
@@ -838,7 +977,7 @@ int findIndexByString(const char *searchString, const char *const *array, int ar
// Durchlaufe das Array und vergleiche jeden String
for (int i = 0; i < arraySize; ++i)
{
if (strcmp(array[i], searchString) == 0)
if (array[i] && strcmp(array[i], searchString) == 0)
{
// String gefunden, gib den Index zurück
return i;
@@ -862,7 +1001,7 @@ int findIndexByString(const char *searchString, const char *const *array, int ar
*/
void Websocket_PushNotification(String Message, NotificationType_t type)
{
String typeString = "";
String typeString;
switch (type)
{
case info:
@@ -877,7 +1016,10 @@ void Websocket_PushNotification(String Message, NotificationType_t type)
case error:
typeString = "danger";
break;
default:
typeString = "info";
break;
}
webSocket.textAll("NOTIFY:" + typeString + ";" + Message);
Debug_pushMessage("Sending Notification to WebUI: %s\n", typeString);
Debug_pushMessage("Sending Notification to WebUI: %s\n", typeString.c_str());
}