Adicionar primeiro

This commit is contained in:
2025-06-06 21:17:25 +01:00
parent c188084ba4
commit 282e7f517b
841 changed files with 199592 additions and 1 deletions

6
CMakeLists.txt Executable file
View File

@@ -0,0 +1,6 @@
# The following lines of boilerplate have to be in your project's
# CMakeLists in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.16)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(esp32-evse)

674
LICENSE.md Executable 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>.

View File

@@ -1 +1,84 @@
# chargeflow ![ESP32 EVSE](https://github.com/dzurikmiroslav/esp32-evse/wiki/images/logo-full.svg)
J1772 EVSE firmware for ESP32 based devices.
![Build with ESP-IDF](https://github.com/dzurikmiroslav/esp32-evse/workflows/Build%20with%20ESP-IDF/badge.svg)
[![License](https://img.shields.io/github/license/dzurikmiroslav/esp32-evse.svg)](LICENSE.md)
## Key features
- Hardware abstraction for device design
- Responsive web-interface
- OTA update
- Integrated energy meter
- [REST](https://github.com/dzurikmiroslav/esp32-evse/wiki/Rest) API
- MQTT API
- [Modbus](https://github.com/dzurikmiroslav/esp32-evse/wiki/Modbus) (RS485, TCP)
- [Scripting](https://github.com/dzurikmiroslav/esp32-evse/wiki/Script)
- [Nextion HMI](https://github.com/dzurikmiroslav/esp32-evse/wiki/Nextion)
### Device definition method
_One firmware to rule them all._ Not really :-) one per device platform (ESP32, ESP32-S2...).
There is no need to compile the firmware for your EVSE design.
Source code ist not hardcoded to GPIOs or other hardware design features.
All code is written in ESP-IDF without additional mapping layer like Arduino.
All configuration is written outside firmware in configuration file named _board.cfg_ on dedicated partition.
For example, on following scheme is minimal EVSE circuit with ESP32 devkit.
![Minimal circuit](https://github.com/dzurikmiroslav/esp32-evse/wiki/images/minimal-circuit.png)
For this circuit there is _board.cfg_, for more information's see [Wiki](https://github.com/dzurikmiroslav/esp32-evse/wiki/Board-config).
```bash
#Device name
DEVICE_NAME=ESP32 minimal EVSE
#Button
BUTTON_WIFI_GPIO=0
#Pilot
PILOT_PWM_GPIO=33
PILOT_ADC_CHANNEL=7
PILOT_DOWN_THRESHOLD_12=2410
PILOT_DOWN_THRESHOLD_9=2104
PILOT_DOWN_THRESHOLD_6=1797
PILOT_DOWN_THRESHOLD_3=1491
PILOT_DOWN_THRESHOLD_N12=265
#AC relay
AC_RELAY_GPIO=32
```
### Web interface
Fully responsive web interface is accessible local network IP address on port 80.
Dashboard page
![Dashboard](https://github.com/dzurikmiroslav/esp32-evse/wiki/images/web-dashboard.png)
Settings page
![Settings](https://github.com/dzurikmiroslav/esp32-evse/wiki/images/web-settings.png)
Mobile dashboard page
![Dashboard mobile](https://github.com/dzurikmiroslav/esp32-evse/wiki/images/web-dashboard-mobile.png)
## Hardware
### ESP32DevkitC
Dev board with basic functionality, single phase energy meter, RS485. One side pcb, for DIY makers easy to make at home conditions ;-)
[EasyEDA project](https://oshwlab.com/dzurik.miroslav/esp32-devkit-evse)
![ESP32DevkitC](https://github.com/dzurikmiroslav/esp32-evse/wiki/images/esp32devkitc.jpg)
### ESP32-S2 DIY ALPHA
ESP32-S2 based EVSE with advanced functionality, three phase energy meter, RS485, UART, 1WIRE, RCM, socket lock.
[EasyEDA project](https://oshwlab.com/dzurik.miroslav/esp32s2-diy-evse)
![ESP32-S2-DA](https://github.com/dzurikmiroslav/esp32-evse/wiki/images/esp32s2da.jpg)

66
cfg/custom/board.cfg Executable file
View File

@@ -0,0 +1,66 @@
DEVICE_NAME=Custom EVSE
#LEDs
LED_CHARGING=n
LED_CHARGING_GPIO=
LED_ERROR=n
LED_ERROR_GPIO=
LED_STOP=n
LED_STOP_GPIO=
#Button
BUTTON_WIFI_GPIO=32
#Pilot
PILOT_PWM_GPIO=1
PILOT_ADC_CHANNEL=1
PILOT_DOWN_THRESHOLD_12=2600
PILOT_DOWN_THRESHOLD_9=2200
PILOT_DOWN_THRESHOLD_6=1900
PILOT_DOWN_THRESHOLD_3=1600
PILOT_DOWN_THRESHOLD_N12=700
#Proximity
PROXIMITY=n
PROXIMITY_ADC_CHANNEL=1
PROXIMITY_DOWN_THRESHOLD_13=1650
PROXIMITY_DOWN_THRESHOLD_20=820
PROXIMITY_DOWN_THRESHOLD_32=430
#AC relay
AC_RELAY_GPIO=25
#Cable lock
SOCKET_LOCK=n
SOCKET_LOCK_A_GPIO=
SOCKET_LOCK_B_GPIO=
SOCKET_LOCK_DETECTION_GPIO=
#Energy meter (none | cur | cur_vlt)
ENERGY_METER=none
ENERGY_METER_THREE_PHASES=n
#Energy meter internal (ENERGY_METER=cur | cur_vlt)
ENERGY_METER_L1_CUR_ADC_CHANNEL=
ENERGY_METER_L2_CUR_ADC_CHANNEL=
ENERGY_METER_L3_CUR_ADC_CHANNEL=
ENERGY_METER_CUR_SCALE=
#Energy meter internal (ENERGY_METER=cur_vlt)
ENERGY_METER_L1_VLT_ADC_CHANNEL=
ENERGY_METER_L2_VLT_ADC_CHANNEL=
ENERGY_METER_L3_VLT_ADC_CHANNEL=
ENERGY_METER_VLT_SCALE=
#Serial (SERIAL_X=none|uart|rs485)
SERIAL_1=none
SERIAL_1_NAME=UART 1
SERIAL_1_RXD_GPIO=
SERIAL_1_TXD_GPIO=
SERIAL_1_RTS_GPIO=
SERIAL_2=none
SERIAL_2_NAME=UART 2
SERIAL_2_RXD_GPIO=
SERIAL_2_TXD_GPIO=
SERIAL_2_RTS_GPIO=

125
cfg/esp32devkitc/board.cfg Executable file
View File

@@ -0,0 +1,125 @@
DEVICE_NAME=Plixin Evse
#LEDs
LED_CHARGING=y
LED_CHARGING_GPIO=14
LED_ERROR=y
LED_ERROR_GPIO=13
LED_STOP=y
LED_STOP_GPIO=12
#BUZZER
BUZZER=y
BUZZER_GPIO=21
#Button
BUTTON_WIFI_GPIO=32
#Pilot
PILOT_PWM_GPIO=33
PILOT_ADC_CHANNEL=6
PILOT_DOWN_THRESHOLD_12=3000
PILOT_DOWN_THRESHOLD_9=2600
PILOT_DOWN_THRESHOLD_6=2200
PILOT_DOWN_THRESHOLD_3=1950
PILOT_DOWN_THRESHOLD_N12=500
#Proximity
PROXIMITY=y
PROXIMITY_ADC_CHANNEL=3
PROXIMITY_DOWN_THRESHOLD_8=2450
PROXIMITY_DOWN_THRESHOLD_10=2050
PROXIMITY_DOWN_THRESHOLD_13=1650
PROXIMITY_DOWN_THRESHOLD_20=820
PROXIMITY_DOWN_THRESHOLD_25=610
PROXIMITY_DOWN_THRESHOLD_32=430
#AC relay
AC_RELAY_GPIO=25
#Cable lock
SOCKET_LOCK=n
SOCKET_LOCK_A_GPIO=
SOCKET_LOCK_B_GPIO=
SOCKET_LOCK_DETECTION_GPIO=
#Energy meter (none | cur | cur_vlt)
ENERGY_METER=none
ENERGY_METER_THREE_PHASES=n
#Energy meter internal (ENERGY_METER=cur | cur_vlt)
ENERGY_METER_L1_CUR_ADC_CHANNEL=7
ENERGY_METER_L2_CUR_ADC_CHANNEL=
ENERGY_METER_L3_CUR_ADC_CHANNEL=
ENERGY_METER_CUR_SCALE=0.090909091
#Energy meter internal (ENERGY_METER=cur_vlt)
ENERGY_METER_L1_VLT_ADC_CHANNEL=
ENERGY_METER_L2_VLT_ADC_CHANNEL=
ENERGY_METER_L3_VLT_ADC_CHANNEL=
ENERGY_METER_VLT_SCALE=0.47
#AUX
AUX_IN_1=n
AUX_IN_1_NAME=
AUX_IN_1_GPIO=
AUX_IN_2=n
AUX_IN_2_NAME=
AUX_IN_2_GPIO=
AUX_IN_3=n
AUX_IN_3_NAME=
AUX_IN_3_GPIO=
AUX_IN_4=n
AUX_IN_4_NAME=
AUX_IN_4_GPIO=
AUX_OUT_1=n
AUX_OUT_1_NAME=
AUX_OUT_1_GPIO=
AUX_OUT_2=n
AUX_OUT_2_NAME=
AUX_OUT_2_GPIO=
AUX_OUT_3=n
AUX_OUT_3_NAME=
AUX_OUT_3_GPIO=
AUX_OUT_4=n
AUX_OUT_4_NAME=
AUX_OUT_4_GPIO=
AUX_AIN_1=n
AUX_AIN_1_NAME=
AUX_AIN_1_ADC_CHANNEL=
AUX_AIN_2=n
AUX_AIN_2_NAME=
AUX_AIN_2_ADC_CHANNEL=
#Serial (SERIAL_X=none|uart|rs485)
SERIAL_1=none
SERIAL_1_NAME=UART via USB
SERIAL_1_RXD_GPIO=
SERIAL_1_TXD_GPIO=
SERIAL_1_RTS_GPIO=
SERIAL_2=none
SERIAL_2_NAME=RS485
SERIAL_2_RXD_GPIO=
SERIAL_2_TXD_GPIO=
SERIAL_2_RTS_GPIO=
SERIAL_3=none
SERIAL_3_NAME=UART
SERIAL_3_RXD_GPIO=
SERIAL_3_TXD_GPIO=
SERIAL_3_RTS_GPIO=
#Onewire devices
ONEWIRE=n
ONEWIRE_GPIO=
ONEWIRE_TEMP_SENSOR=n

119
cfg/esp32s2da/board.cfg Executable file
View File

@@ -0,0 +1,119 @@
DEVICE_NAME=ESP32-S2-DA EVSE
#LEDs
LED_CHARGING=y
LED_CHARGING_GPIO=36
LED_ERROR=y
LED_ERROR_GPIO=37
LED_STOP=y
LED_STOP_GPIO=35
#Button
BUTTON_WIFI_GPIO=32
#Pilot
PILOT_PWM_GPIO=33
PILOT_ADC_CHANNEL=3
PILOT_DOWN_THRESHOLD_12=2405
PILOT_DOWN_THRESHOLD_9=2099
PILOT_DOWN_THRESHOLD_6=1792
PILOT_DOWN_THRESHOLD_3=1484
PILOT_DOWN_THRESHOLD_N12=728
#Proximity
PROXIMITY=n
PROXIMITY_ADC_CHANNEL=2
PROXIMITY_DOWN_THRESHOLD_13=1650
PROXIMITY_DOWN_THRESHOLD_20=820
PROXIMITY_DOWN_THRESHOLD_32=430
#AC relay
AC_RELAY_GPIO=25
#Socket lock
SOCKET_LOCK=n
SOCKET_LOCK_A_GPIO=20
SOCKET_LOCK_B_GPIO=19
SOCKET_LOCK_DETECTION_GPIO=34
SOCKET_LOCK_DETECTION_DELAY=1000
SOCKET_LOCK_MIN_BREAK_TIME=1000
#Residual current monitor
RCM=n
RCM_GPIO=41
RCM_TEST_GPIO=26
#Energy meter (none | cur | cur_vlt)
ENERGY_METER=cur_vlt
ENERGY_METER_THREE_PHASES=y
#Energy meter internal (ENERGY_METER=cur | cur_vlt)
ENERGY_METER_L1_CUR_ADC_CHANNEL=4
ENERGY_METER_L2_CUR_ADC_CHANNEL=5
ENERGY_METER_L3_CUR_ADC_CHANNEL=6
ENERGY_METER_CUR_SCALE=0.090909091
#Energy meter internal (ENERGY_METER=cur_vlt)
ENERGY_METER_L1_VLT_ADC_CHANNEL=7
ENERGY_METER_L2_VLT_ADC_CHANNEL=8
ENERGY_METER_L3_VLT_ADC_CHANNEL=9
ENERGY_METER_VLT_SCALE=0.47
#AUX
AUX_IN_1=n
AUX_IN_1_NAME=
AUX_IN_1_GPIO=
AUX_IN_2=n
AUX_IN_2_NAME=
AUX_IN_2_GPIO=
AUX_IN_3=n
AUX_IN_3_NAME=
AUX_IN_3_GPIO=
AUX_IN_4=n
AUX_IN_4_NAME=
AUX_IN_4_GPIO=
AUX_OUT_1=n
AUX_OUT_1_NAME=
AUX_OUT_1_GPIO=
AUX_OUT_2=n
AUX_OUT_2_NAME=
AUX_OUT_2_GPIO=
AUX_OUT_3=n
AUX_OUT_3_NAME=
AUX_OUT_3_GPIO=
AUX_OUT_4=n
AUX_OUT_4_NAME=
AUX_OUT_4_GPIO=
AUX_AIN_1=n
AUX_AIN_1_NAME=
AUX_AIN_1_ADC_CHANNEL=
AUX_AIN_2=n
AUX_AIN_2_NAME=
AUX_AIN_2_ADC_CHANNEL=
#Serial (SERIAL_X=none|uart|rs485)
SERIAL_1=none
SERIAL_1_NAME=UART
SERIAL_1_RXD_GPIO=
SERIAL_1_TXD_GPIO=
SERIAL_1_RTS_GPIO=
SERIAL_2=none
SERIAL_2_NAME=RS-485
SERIAL_2_RXD_GPIO=
SERIAL_2_TXD_GPIO=
SERIAL_2_RTS_GPIO=
#Onewire devices
ONEWIRE=n
ONEWIRE_GPIO=
ONEWIRE_TEMP_SENSOR=n

14
components/api/CMakeLists.txt Executable file
View File

@@ -0,0 +1,14 @@
set(srcs
"src/api.c"
"src/ota.c"
"src/json.c"
"src/timeout_utils.c"
"lib/cAT/src/cat.c")
idf_component_register(SRCS "${srcs}"
INCLUDE_DIRS "include" "lib/cAT/src"
PRIV_INCLUDE_DIRS "src"
PRIV_REQUIRES nvs_flash app_update json driver esp_http_client esp_netif esp_wifi esp_timer esp_hw_support
REQUIRES network config evse peripherals protocols serial_mdb ocpp)
set_source_files_properties(lib/cAT/src/cat.c PROPERTIES COMPILE_FLAGS -Wno-maybe-uninitialized)

6
components/api/include/api.h Executable file
View File

@@ -0,0 +1,6 @@
#ifndef API_H_
#define API_H_
void api_init(void);
#endif /* API_H_ */

43
components/api/include/json.h Executable file
View File

@@ -0,0 +1,43 @@
#ifndef JSON_UTILS_H
#define JSON_UTILS_H
#include "esp_err.h"
#include "cJSON.h"
cJSON* json_get_evse_config(void);
esp_err_t json_set_evse_config(cJSON* root);
cJSON* json_get_wifi_config(void);
esp_err_t json_set_wifi_config(cJSON* root, bool timeout);
cJSON* json_get_wifi_scan(void);
cJSON* json_get_mqtt_config(void);
esp_err_t json_set_mqtt_config(cJSON* root);
//cJSON* json_get_serial_config(void);
//esp_err_t json_set_serial_config(cJSON* root);
cJSON* json_get_modbus_config(void);
esp_err_t json_set_modbus_config(cJSON* root);
//cJSON* json_get_script_config(void);
//esp_err_t json_set_script_config(cJSON* root);
cJSON* json_get_time_config(void);
esp_err_t json_set_time_config(cJSON* root);
cJSON* json_get_state(void);
cJSON* json_get_info(void);
cJSON* json_get_board_config(void);
#endif /* JSON_UTILS_H */

15
components/api/include/ota.h Executable file
View File

@@ -0,0 +1,15 @@
#ifndef OTA_H_
#define OTA_H_
#include <stdbool.h>
#include "esp_err.h"
#define OTA_VERSION_URL "https://dzurikmiroslav.github.io/esp32-evse/firmware/version.txt"
#define OTA_FIRMWARE_URL "https://dzurikmiroslav.github.io/esp32-evse/firmware/"
esp_err_t ota_get_available_version(char* version);
bool ota_is_newer_version(const char* actual, const char* available);
#endif /* OTA_H_ */

View File

@@ -0,0 +1,23 @@
#ifndef TIMEOUT_UTILS_H
#define TIMEOUT_UTILS_H
#include <stdbool.h>
#include "esp_err.h"
/**
* @brief Restart in 5 seconds
*
*/
void timeout_restart(void);
/**
* @brief Set WiFi config in 1 second
*
* @param enabled
* @param ssid
* @param password
* @return esp_err_t
*/
esp_err_t timeout_wifi_set_config(bool enabled, const char* ssid, const char* password);
#endif /* TIMEOUT_UTILS_H */

View File

@@ -0,0 +1,493 @@
# SPDX-License-Identifier: GPL-2.0
#
# clang-format configuration file. Intended for clang-format >= 4.
#
# For more information, see:
#
# Documentation/process/clang-format.rst
# https://clang.llvm.org/docs/ClangFormat.html
# https://clang.llvm.org/docs/ClangFormatStyleOptions.html
#
---
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignConsecutiveAssignments: false
AlignConsecutiveDeclarations: false
#AlignEscapedNewlines: Left # Unknown to clang-format-4.0
AlignOperands: true
AlignTrailingComments: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: None
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: false
BinPackArguments: true
BinPackParameters: true
BraceWrapping:
AfterClass: false
AfterControlStatement: false
AfterEnum: false
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
#AfterExternBlock: false # Unknown to clang-format-5.0
BeforeCatch: false
BeforeElse: false
IndentBraces: false
#SplitEmptyFunction: true # Unknown to clang-format-4.0
#SplitEmptyRecord: true # Unknown to clang-format-4.0
#SplitEmptyNamespace: true # Unknown to clang-format-4.0
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Custom
#BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0
BreakBeforeTernaryOperators: false
BreakConstructorInitializersBeforeComma: false
#BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 160
CommentPragmas: '^ IWYU pragma:'
#CompactNamespaces: false # Unknown to clang-format-4.0
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 8
ContinuationIndentWidth: 8
Cpp11BracedListStyle: false
DerivePointerAlignment: false
DisableFormat: false
ExperimentalAutoDetectBinPacking: false
#FixNamespaceComments: false # Unknown to clang-format-4.0
# Taken from:
# git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ \
# | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \
# | sort | uniq
ForEachMacros:
- 'apei_estatus_for_each_section'
- 'ata_for_each_dev'
- 'ata_for_each_link'
- '__ata_qc_for_each'
- 'ata_qc_for_each'
- 'ata_qc_for_each_raw'
- 'ata_qc_for_each_with_internal'
- 'ax25_for_each'
- 'ax25_uid_for_each'
- '__bio_for_each_bvec'
- 'bio_for_each_bvec'
- 'bio_for_each_integrity_vec'
- '__bio_for_each_segment'
- 'bio_for_each_segment'
- 'bio_for_each_segment_all'
- 'bio_list_for_each'
- 'bip_for_each_vec'
- 'blkg_for_each_descendant_post'
- 'blkg_for_each_descendant_pre'
- 'blk_queue_for_each_rl'
- 'bond_for_each_slave'
- 'bond_for_each_slave_rcu'
- 'bpf_for_each_spilled_reg'
- 'btree_for_each_safe128'
- 'btree_for_each_safe32'
- 'btree_for_each_safe64'
- 'btree_for_each_safel'
- 'card_for_each_dev'
- 'cgroup_taskset_for_each'
- 'cgroup_taskset_for_each_leader'
- 'cpufreq_for_each_entry'
- 'cpufreq_for_each_entry_idx'
- 'cpufreq_for_each_valid_entry'
- 'cpufreq_for_each_valid_entry_idx'
- 'css_for_each_child'
- 'css_for_each_descendant_post'
- 'css_for_each_descendant_pre'
- 'device_for_each_child_node'
- 'drm_atomic_crtc_for_each_plane'
- 'drm_atomic_crtc_state_for_each_plane'
- 'drm_atomic_crtc_state_for_each_plane_state'
- 'drm_atomic_for_each_plane_damage'
- 'drm_connector_for_each_possible_encoder'
- 'drm_for_each_connector_iter'
- 'drm_for_each_crtc'
- 'drm_for_each_encoder'
- 'drm_for_each_encoder_mask'
- 'drm_for_each_fb'
- 'drm_for_each_legacy_plane'
- 'drm_for_each_plane'
- 'drm_for_each_plane_mask'
- 'drm_for_each_privobj'
- 'drm_mm_for_each_hole'
- 'drm_mm_for_each_node'
- 'drm_mm_for_each_node_in_range'
- 'drm_mm_for_each_node_safe'
- 'flow_action_for_each'
- 'for_each_active_drhd_unit'
- 'for_each_active_iommu'
- 'for_each_available_child_of_node'
- 'for_each_bio'
- 'for_each_board_func_rsrc'
- 'for_each_bvec'
- 'for_each_card_components'
- 'for_each_card_links'
- 'for_each_card_links_safe'
- 'for_each_card_prelinks'
- 'for_each_card_rtds'
- 'for_each_card_rtds_safe'
- 'for_each_cgroup_storage_type'
- 'for_each_child_of_node'
- 'for_each_clear_bit'
- 'for_each_clear_bit_from'
- 'for_each_cmsghdr'
- 'for_each_compatible_node'
- 'for_each_component_dais'
- 'for_each_component_dais_safe'
- 'for_each_comp_order'
- 'for_each_console'
- 'for_each_cpu'
- 'for_each_cpu_and'
- 'for_each_cpu_not'
- 'for_each_cpu_wrap'
- 'for_each_dev_addr'
- 'for_each_dma_cap_mask'
- 'for_each_dpcm_be'
- 'for_each_dpcm_be_rollback'
- 'for_each_dpcm_be_safe'
- 'for_each_dpcm_fe'
- 'for_each_drhd_unit'
- 'for_each_dss_dev'
- 'for_each_efi_memory_desc'
- 'for_each_efi_memory_desc_in_map'
- 'for_each_element'
- 'for_each_element_extid'
- 'for_each_element_id'
- 'for_each_endpoint_of_node'
- 'for_each_evictable_lru'
- 'for_each_fib6_node_rt_rcu'
- 'for_each_fib6_walker_rt'
- 'for_each_free_mem_range'
- 'for_each_free_mem_range_reverse'
- 'for_each_func_rsrc'
- 'for_each_hstate'
- 'for_each_if'
- 'for_each_iommu'
- 'for_each_ip_tunnel_rcu'
- 'for_each_irq_nr'
- 'for_each_link_codecs'
- 'for_each_lru'
- 'for_each_matching_node'
- 'for_each_matching_node_and_match'
- 'for_each_memblock'
- 'for_each_memblock_type'
- 'for_each_memcg_cache_index'
- 'for_each_mem_pfn_range'
- 'for_each_mem_range'
- 'for_each_mem_range_rev'
- 'for_each_migratetype_order'
- 'for_each_msi_entry'
- 'for_each_msi_entry_safe'
- 'for_each_net'
- 'for_each_netdev'
- 'for_each_netdev_continue'
- 'for_each_netdev_continue_rcu'
- 'for_each_netdev_feature'
- 'for_each_netdev_in_bond_rcu'
- 'for_each_netdev_rcu'
- 'for_each_netdev_reverse'
- 'for_each_netdev_safe'
- 'for_each_net_rcu'
- 'for_each_new_connector_in_state'
- 'for_each_new_crtc_in_state'
- 'for_each_new_mst_mgr_in_state'
- 'for_each_new_plane_in_state'
- 'for_each_new_private_obj_in_state'
- 'for_each_node'
- 'for_each_node_by_name'
- 'for_each_node_by_type'
- 'for_each_node_mask'
- 'for_each_node_state'
- 'for_each_node_with_cpus'
- 'for_each_node_with_property'
- 'for_each_of_allnodes'
- 'for_each_of_allnodes_from'
- 'for_each_of_cpu_node'
- 'for_each_of_pci_range'
- 'for_each_old_connector_in_state'
- 'for_each_old_crtc_in_state'
- 'for_each_old_mst_mgr_in_state'
- 'for_each_oldnew_connector_in_state'
- 'for_each_oldnew_crtc_in_state'
- 'for_each_oldnew_mst_mgr_in_state'
- 'for_each_oldnew_plane_in_state'
- 'for_each_oldnew_plane_in_state_reverse'
- 'for_each_oldnew_private_obj_in_state'
- 'for_each_old_plane_in_state'
- 'for_each_old_private_obj_in_state'
- 'for_each_online_cpu'
- 'for_each_online_node'
- 'for_each_online_pgdat'
- 'for_each_pci_bridge'
- 'for_each_pci_dev'
- 'for_each_pci_msi_entry'
- 'for_each_populated_zone'
- 'for_each_possible_cpu'
- 'for_each_present_cpu'
- 'for_each_prime_number'
- 'for_each_prime_number_from'
- 'for_each_process'
- 'for_each_process_thread'
- 'for_each_property_of_node'
- 'for_each_registered_fb'
- 'for_each_reserved_mem_region'
- 'for_each_rtd_codec_dai'
- 'for_each_rtd_codec_dai_rollback'
- 'for_each_rtdcom'
- 'for_each_rtdcom_safe'
- 'for_each_set_bit'
- 'for_each_set_bit_from'
- 'for_each_sg'
- 'for_each_sg_dma_page'
- 'for_each_sg_page'
- 'for_each_sibling_event'
- 'for_each_subelement'
- 'for_each_subelement_extid'
- 'for_each_subelement_id'
- '__for_each_thread'
- 'for_each_thread'
- 'for_each_zone'
- 'for_each_zone_zonelist'
- 'for_each_zone_zonelist_nodemask'
- 'fwnode_for_each_available_child_node'
- 'fwnode_for_each_child_node'
- 'fwnode_graph_for_each_endpoint'
- 'gadget_for_each_ep'
- 'genradix_for_each'
- 'genradix_for_each_from'
- 'hash_for_each'
- 'hash_for_each_possible'
- 'hash_for_each_possible_rcu'
- 'hash_for_each_possible_rcu_notrace'
- 'hash_for_each_possible_safe'
- 'hash_for_each_rcu'
- 'hash_for_each_safe'
- 'hctx_for_each_ctx'
- 'hlist_bl_for_each_entry'
- 'hlist_bl_for_each_entry_rcu'
- 'hlist_bl_for_each_entry_safe'
- 'hlist_for_each'
- 'hlist_for_each_entry'
- 'hlist_for_each_entry_continue'
- 'hlist_for_each_entry_continue_rcu'
- 'hlist_for_each_entry_continue_rcu_bh'
- 'hlist_for_each_entry_from'
- 'hlist_for_each_entry_from_rcu'
- 'hlist_for_each_entry_rcu'
- 'hlist_for_each_entry_rcu_bh'
- 'hlist_for_each_entry_rcu_notrace'
- 'hlist_for_each_entry_safe'
- '__hlist_for_each_rcu'
- 'hlist_for_each_safe'
- 'hlist_nulls_for_each_entry'
- 'hlist_nulls_for_each_entry_from'
- 'hlist_nulls_for_each_entry_rcu'
- 'hlist_nulls_for_each_entry_safe'
- 'i3c_bus_for_each_i2cdev'
- 'i3c_bus_for_each_i3cdev'
- 'ide_host_for_each_port'
- 'ide_port_for_each_dev'
- 'ide_port_for_each_present_dev'
- 'idr_for_each_entry'
- 'idr_for_each_entry_continue'
- 'idr_for_each_entry_ul'
- 'inet_bind_bucket_for_each'
- 'inet_lhash2_for_each_icsk_rcu'
- 'key_for_each'
- 'key_for_each_safe'
- 'klp_for_each_func'
- 'klp_for_each_func_safe'
- 'klp_for_each_func_static'
- 'klp_for_each_object'
- 'klp_for_each_object_safe'
- 'klp_for_each_object_static'
- 'kvm_for_each_memslot'
- 'kvm_for_each_vcpu'
- 'list_for_each'
- 'list_for_each_codec'
- 'list_for_each_codec_safe'
- 'list_for_each_entry'
- 'list_for_each_entry_continue'
- 'list_for_each_entry_continue_rcu'
- 'list_for_each_entry_continue_reverse'
- 'list_for_each_entry_from'
- 'list_for_each_entry_from_rcu'
- 'list_for_each_entry_from_reverse'
- 'list_for_each_entry_lockless'
- 'list_for_each_entry_rcu'
- 'list_for_each_entry_reverse'
- 'list_for_each_entry_safe'
- 'list_for_each_entry_safe_continue'
- 'list_for_each_entry_safe_from'
- 'list_for_each_entry_safe_reverse'
- 'list_for_each_prev'
- 'list_for_each_prev_safe'
- 'list_for_each_safe'
- 'llist_for_each'
- 'llist_for_each_entry'
- 'llist_for_each_entry_safe'
- 'llist_for_each_safe'
- 'media_device_for_each_entity'
- 'media_device_for_each_intf'
- 'media_device_for_each_link'
- 'media_device_for_each_pad'
- 'mp_bvec_for_each_page'
- 'mp_bvec_for_each_segment'
- 'nanddev_io_for_each_page'
- 'netdev_for_each_lower_dev'
- 'netdev_for_each_lower_private'
- 'netdev_for_each_lower_private_rcu'
- 'netdev_for_each_mc_addr'
- 'netdev_for_each_uc_addr'
- 'netdev_for_each_upper_dev_rcu'
- 'netdev_hw_addr_list_for_each'
- 'nft_rule_for_each_expr'
- 'nla_for_each_attr'
- 'nla_for_each_nested'
- 'nlmsg_for_each_attr'
- 'nlmsg_for_each_msg'
- 'nr_neigh_for_each'
- 'nr_neigh_for_each_safe'
- 'nr_node_for_each'
- 'nr_node_for_each_safe'
- 'of_for_each_phandle'
- 'of_property_for_each_string'
- 'of_property_for_each_u32'
- 'pci_bus_for_each_resource'
- 'ping_portaddr_for_each_entry'
- 'plist_for_each'
- 'plist_for_each_continue'
- 'plist_for_each_entry'
- 'plist_for_each_entry_continue'
- 'plist_for_each_entry_safe'
- 'plist_for_each_safe'
- 'pnp_for_each_card'
- 'pnp_for_each_dev'
- 'protocol_for_each_card'
- 'protocol_for_each_dev'
- 'queue_for_each_hw_ctx'
- 'radix_tree_for_each_slot'
- 'radix_tree_for_each_tagged'
- 'rbtree_postorder_for_each_entry_safe'
- 'rdma_for_each_port'
- 'resource_list_for_each_entry'
- 'resource_list_for_each_entry_safe'
- 'rhl_for_each_entry_rcu'
- 'rhl_for_each_rcu'
- 'rht_for_each'
- 'rht_for_each_from'
- 'rht_for_each_entry'
- 'rht_for_each_entry_from'
- 'rht_for_each_entry_rcu'
- 'rht_for_each_entry_rcu_from'
- 'rht_for_each_entry_safe'
- 'rht_for_each_rcu'
- 'rht_for_each_rcu_from'
- '__rq_for_each_bio'
- 'rq_for_each_bvec'
- 'rq_for_each_segment'
- 'scsi_for_each_prot_sg'
- 'scsi_for_each_sg'
- 'sctp_for_each_hentry'
- 'sctp_skb_for_each'
- 'shdma_for_each_chan'
- '__shost_for_each_device'
- 'shost_for_each_device'
- 'sk_for_each'
- 'sk_for_each_bound'
- 'sk_for_each_entry_offset_rcu'
- 'sk_for_each_from'
- 'sk_for_each_rcu'
- 'sk_for_each_safe'
- 'sk_nulls_for_each'
- 'sk_nulls_for_each_from'
- 'sk_nulls_for_each_rcu'
- 'snd_array_for_each'
- 'snd_pcm_group_for_each_entry'
- 'snd_soc_dapm_widget_for_each_path'
- 'snd_soc_dapm_widget_for_each_path_safe'
- 'snd_soc_dapm_widget_for_each_sink_path'
- 'snd_soc_dapm_widget_for_each_source_path'
- 'tb_property_for_each'
- 'tcf_exts_for_each_action'
- 'udp_portaddr_for_each_entry'
- 'udp_portaddr_for_each_entry_rcu'
- 'usb_hub_for_each_child'
- 'v4l2_device_for_each_subdev'
- 'v4l2_m2m_for_each_dst_buf'
- 'v4l2_m2m_for_each_dst_buf_safe'
- 'v4l2_m2m_for_each_src_buf'
- 'v4l2_m2m_for_each_src_buf_safe'
- 'virtio_device_for_each_vq'
- 'xa_for_each'
- 'xa_for_each_marked'
- 'xa_for_each_start'
- 'xas_for_each'
- 'xas_for_each_conflict'
- 'xas_for_each_marked'
- 'zorro_for_each_dev'
#IncludeBlocks: Preserve # Unknown to clang-format-5.0
IncludeCategories:
- Regex: '.*'
Priority: 1
IncludeIsMainRegex: '(Test)?$'
IndentCaseLabels: false
#IndentPPDirectives: None # Unknown to clang-format-5.0
IndentWidth: 8
IndentWrappedFunctionNames: false
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: false
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 1
NamespaceIndentation: Inner
#ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0
ObjCBlockIndentWidth: 8
ObjCSpaceAfterProperty: true
ObjCSpaceBeforeProtocolList: true
# Taken from git's rules
#PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0
PenaltyBreakBeforeFirstCallParameter: 30
PenaltyBreakComment: 10
PenaltyBreakFirstLessLess: 0
PenaltyBreakString: 10
PenaltyExcessCharacter: 100
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
ReflowComments: false
SortIncludes: false
#SortUsingDeclarations: false # Unknown to clang-format-4.0
SpaceAfterCStyleCast: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
#SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0
#SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0
SpaceBeforeParens: ControlStatements
#SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: false
SpacesInContainerLiterals: false
SpacesInCStyleCastParentheses: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: Cpp03
TabWidth: 8
UseTab: Never
...

17
components/api/lib/cAT/.gitignore vendored Executable file
View File

@@ -0,0 +1,17 @@
.vscode
lib
bin
dist
build
CMakeLists.txt.user
CMakeCache.txt
CMakeFiles
CMakeScripts
Testing
Makefile
cmake_install.cmake
install_manifest.txt
compile_commands.json
CTestTestfile.cmake
_deps

View File

@@ -0,0 +1,11 @@
language: c
compiler:
- gcc
before_script:
- mkdir build
- cd build
- cmake ..
script: make && make test

View File

@@ -0,0 +1,148 @@
cmake_minimum_required( VERSION 3.0 )
project( libcat LANGUAGES C )
set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
set( CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib )
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin )
enable_testing( )
include_directories( ${PROJECT_SOURCE_DIR}/src )
file( GLOB SRC_FILES src/*.c )
add_library( cat SHARED ${SRC_FILES} )
set_target_properties( cat PROPERTIES VERSION 0.11.1 SOVERSION 1 )
target_compile_options( cat PRIVATE -Werror -Wall -Wextra -pedantic )
install( TARGETS cat DESTINATION lib )
install( FILES src/cat.h DESTINATION include/cat )
add_executable( demo example/demo.c )
target_link_libraries( demo cat )
add_executable( basic example/basic.c )
target_link_libraries( basic cat )
add_executable( unsolicited example/unsolicited.c )
target_link_libraries( unsolicited cat )
add_executable( test_parse tests/test_parse.c )
target_link_libraries( test_parse cat )
add_test( test_parse ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_parse )
add_executable( test_run tests/test_run.c )
target_link_libraries( test_run cat )
add_test( test_run ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_run )
add_executable( test_read tests/test_read.c )
target_link_libraries( test_read cat )
add_test( test_read ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_read )
add_executable( test_write tests/test_write.c )
target_link_libraries( test_write cat )
add_test( test_write ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_write )
add_executable( test_write_parse tests/test_write_parse.c )
target_link_libraries( test_write_parse cat )
add_test( test_write_parse ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_write_parse )
add_executable( test_write_int_range tests/test_write_int_range.c )
target_link_libraries( test_write_int_range cat )
add_test( test_write_int_range ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_write_int_range )
add_executable( test_write_uint_range tests/test_write_uint_range.c )
target_link_libraries( test_write_uint_range cat )
add_test( test_write_uint_range ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_write_uint_range )
add_executable( test_write_hex_range tests/test_write_hex_range.c )
target_link_libraries( test_write_hex_range cat )
add_test( test_write_hex_range ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_write_hex_range )
add_executable( test_write_hex_buffer tests/test_write_hex_buffer.c )
target_link_libraries( test_write_hex_buffer cat )
add_test( test_write_hex_buffer ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_write_hex_buffer )
add_executable( test_write_string_buffer tests/test_write_string_buffer.c )
target_link_libraries( test_write_string_buffer cat )
add_test( test_write_string_buffer ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_write_string_buffer )
add_executable( test_read_args tests/test_read_args.c )
target_link_libraries( test_read_args cat )
add_test( test_read_args ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_read_args )
add_executable( test_test tests/test_test.c )
target_link_libraries( test_test cat )
add_test( test_test ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_test )
add_executable( test_test_args tests/test_test_args.c )
target_link_libraries( test_test_args cat )
add_test( test_test_args ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_test_args )
add_executable( test_mutex tests/test_mutex.c )
target_link_libraries( test_mutex cat )
add_test( test_mutex ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_mutex )
add_executable( test_unsolicited_read tests/test_unsolicited_read.c )
target_link_libraries( test_unsolicited_read cat )
add_test( test_unsolicited_read ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_unsolicited_read )
add_executable( test_unsolicited_read_stress tests/test_unsolicited_read_stress.c )
target_link_libraries( test_unsolicited_read_stress cat )
add_test( test_unsolicited_read_stress ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_unsolicited_read_stress )
add_executable( test_unsolicited_read_buffer tests/test_unsolicited_read_buffer.c ${SRC_FILES})
set_target_properties( test_unsolicited_read_buffer PROPERTIES COMPILE_DEFINITIONS "CAT_UNSOLICITED_CMD_BUFFER_SIZE=2" )
add_test( test_unsolicited_read_buffer ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_unsolicited_read_buffer )
add_executable( test_hold_state tests/test_hold_state.c )
target_link_libraries( test_hold_state cat )
add_test( test_hold_state ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_hold_state )
add_executable( test_return_read tests/test_return_read.c )
target_link_libraries( test_return_read cat )
add_test( test_return_read ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_return_read )
add_executable( test_return_write tests/test_return_write.c )
target_link_libraries( test_return_write cat )
add_test( test_return_write ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_return_write )
add_executable( test_unsolicited_test tests/test_unsolicited_test.c )
target_link_libraries( test_unsolicited_test cat )
add_test( test_unsolicited_test ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_unsolicited_test )
add_executable( test_return_test tests/test_return_test.c )
target_link_libraries( test_return_test cat )
add_test( test_return_test ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_return_test )
add_executable( test_return_run tests/test_return_run.c )
target_link_libraries( test_return_run cat )
add_test( test_return_run ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_return_run )
add_executable( test_test_only tests/test_test_only.c )
target_link_libraries( test_test_only cat )
add_test( test_test_only ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_test_only )
add_executable( test_search_cmd tests/test_search_cmd.c )
target_link_libraries( test_search_cmd cat )
add_test( test_search_cmd ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_search_cmd )
add_executable( test_order tests/test_order.c )
target_link_libraries( test_order cat )
add_test( test_order ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_order )
add_executable( test_cmd_list tests/test_cmd_list.c )
target_link_libraries( test_cmd_list cat )
add_test( test_cmd_list ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_cmd_list )
add_executable( test_var_access tests/test_var_access.c )
target_link_libraries( test_var_access cat )
add_test( test_var_access ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_var_access )
add_executable( test_shortcuts tests/test_shortcuts.c )
target_link_libraries( test_shortcuts cat )
add_test( test_shortcuts ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/test_shortcuts )
add_custom_target( check COMMAND ${CMAKE_CTEST_COMMAND} --verbose )
add_custom_target( cleanall COMMAND rm -rf Makefile CMakeCache.txt CMakeFiles/ bin/ lib/ cmake_install.cmake CTestTestfile.cmake Testing/ )
add_custom_target( uninstall COMMAND xargs rm < install_manifest.txt )

21
components/api/lib/cAT/LICENSE Executable file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

211
components/api/lib/cAT/README.md Executable file
View File

@@ -0,0 +1,211 @@
[![Build Status](https://travis-ci.org/marcinbor85/cat.svg?branch=master)](https://travis-ci.org/marcinbor85/cat)
# libcat (cAT)
Plain C library for parsing AT commands for use in host devices.
## Features
* blazing fast, non-blocking, robust implementation
* 100% static implementation (without any dynamic memory allocation)
* very small footprint (both RAM and ROM)
* support for READ, WRITE, TEST and RUN type commands
* commands shortcuts (auto select best command candidate)
* single request - multiple responses
* unsolicited read/test command support
* hold state for delayed responses for time-consuming tasks
* high-level memory variables mapping arguments parsing
* variables accessors (read and write, read only, write only)
* automatic arguments types validating
* automatic format test responses for commands with variables
* CRLF and LF compatible
* case-insensitive
* dedicated for embedded systems
* object-oriented architecture
* separated interface for low-level layer
* fully asynchronous input/output operations
* multiplatform and portable
* asynchronous api with event callbacks
* print registered commands list feature
* only two source files
* wide unit tests
## Build
Build and install:
```sh
cmake .
make
make test
sudo make install
```
## Example basic demo posibilities
```console
AT+PRINT=? # TEST command
+PRINT=<X:UINT8[RW]>,<Y:UINT8[RW]>,<MESSAGE:STRING[RW]> # Automatic response
Printing something special at (X,Y). # Automatic response
OK # Automatic acknowledge
AT+PRINT? # READ command
+PRINT=0,0,"" # Automatic response
OK # Automatic acknowledge
AT+PRINT=xyz,-2 # WRITE command
ERROR # Automatic acknowledge
AT+PRINT=1,2,"test" # WRITE command
OK # Automatic acknowledge
AT+PRINT # RUN command
some printing at (1,2) with text "test" # Manual response
OK # Automatic acknowledge
```
## Example unsolicited demo posibilities
```console
AT+START=? # TEST command
+START=<MODE:UINT32[WO]> # Automatic response
Start scanning after write (0 - wifi, 1 - bluetooth). # Automatic response
OK # Automatic acknowledge
AT+START=0 # WRITE command
+SCAN=-10,"wifi1" # Unsolicited read response
+SCAN=-50,"wifi2" # Unsolicited read response
+SCAN=-20,"wifi3" # Unsolicited read response
OK # Unsolicited acknowledge
AT+START=1 # WRITE command
+SCAN=-20,"bluetooth1" # Unsolicited read response
OK # Unsolicited acknowledge
AT+SCAN=? # TEST command
+SCAN=<RSSI:INT32[RO]>,<SSID:STRING[RO]> # Automatic response
Scan result record. # Automatic response
OK # Automatic acknowledge
```
## Usage
Define High-Level variables:
```c
static uint8_t x;
static uint8_t y;
static char msg[32];
static struct cat_variable go_vars[] = {
{
.type = CAT_VAR_UINT_DEC, /* unsigned int variable */
.data = &x,
.data_size = sizeof(x),
.write = x_write,
.name = "X",
.access = CAT_VAR_ACCESS_READ_WRITE,
},
{
.type = CAT_VAR_UINT_DEC, /* unsigned int variable */
.data = &y,
.data_size = sizeof(y),
.write = y_write,
.access = CAT_VAR_ACCESS_READ_WRITE,
},
{
.type = CAT_VAR_BUF_STRING, /* string variable */
.data = msg,
.data_size = sizeof(msg),
.write = msg_write,
.access = CAT_VAR_ACCESS_READ_WRITE,
}
};
```
Define AT commands descriptor:
```c
static struct cat_command cmds[] = {
{
.name = "TEST",
.read = test_read, /* read handler for ATTEST? command */
.write = test_write, /* write handler for ATTEST={val} command */
.run = test_run /* run handler for ATTEST command */
},
{
.name = "+NUM",
.write = num_write, /* write handler for AT+NUM={val} command */
.read = num_read /* read handler for AT+NUM? command */
},
{
.name = "+GO",
.write = go_write, /* write handler for AT+GO={x},{y},{msg} command */
.var = go_vars, /* attach variables to command */
.var_num = sizeof(go_vars) / sizeof(go_vars[0]),
.need_all_vars = true
},
{
.name = "RESTART",
.run = restart_run /* run handler for ATRESTART command */
}
};
```
Define AT command parser descriptor:
```c
static char working_buf[128]; /* working buffer, must be declared manually */
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = working_buf,
.buf_size = sizeof(working_buf),
};
```
Define IO low-level layer interface:
```c
static int write_char(char ch)
{
putc(ch, stdout);
return 1;
}
static int read_char(char *ch)
{
*ch = getch();
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
```
Initialize AT command parser and run:
```c
struct cat_object at; /* at command parser object */
cat_init(&at, &desc, &iface, NULL); /* initialize at command parser object */
while (1) {
cat_service(&at) /* periodically call at command parser service */
... /* other stuff, running in main loop */
}
```

View File

@@ -0,0 +1,70 @@
TODO:
- differentation of variables for read and write commands
- help command (printing all commands posibilities with descriptions)
- documentation updated (buffer sized, return enum types, write variable nums, buf size hints)
- helper setters and getters for variables
0.11.0
* optional context in commands and data_getter in variables
* optional extended read and write variable handler with parent command
0.10.1
* single working buffer insteads of two separated for atcmd and unsolicited events
0.10.0
* separate atcmd and unsolicited event state machines
0.9.0
* variables accessors
0.8.1
* fix commands shourtcuts
0.8.0
* print commands list feature
0.7.1
* more flexible command group initialization (pointers)
0.7.0
* function for checking unsolicited buffer
* some refactoring regarding unsolicited buffer
* helper function cat_search_variable_by_name added
* commands group with searching feature added
* disable feature for commands and groups added
0.6.0
* async non blocking io->write
* async unsolicited read/test event (injected at idle and hold state)
* hold commands parse processing feature (for delayed unsolicited read responses)
* behavior differentation by callbacks return values
* only-test flag in commands descriptor (for fast disable read/write/run)
* helper function for searching command by name
* multiple responses triggered by single request pattern support
* generic mutex descriptor interface
* return value states enum types
0.5.3
* function for checking internal busy state added
0.5.2
* small fix in auto description response
0.5.1
* description field in command added (used in auto help message)
0.5.0
* test command parser with auto help messages
* output string end-line encoding same as input string
* very basic demo example application added
0.4.0
* high level parsing for command arguments
* int, uint, hex, hexbuf, string argument types
* validating arguments values range
0.3.0
* independent buffers (parsing buffer and state buffer)
0.2.0
* passing command struct instead of command name in command handlers

View File

@@ -0,0 +1,161 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
/* variables assigned to print command */
static uint8_t x;
static uint8_t y;
static char message[16];
/* helper variable used to exit demo code */
static bool quit_flag;
/* run command handler with application dependent login print code */
static int print_run(const struct cat_command *cmd)
{
printf("some printing at (%d,%d) with text \"%s\"\n", x, y, message);
return 0;
}
/* run command handler attached to HELP command for printing commands list */
static int print_cmd_list(const struct cat_command *cmd)
{
return CAT_RETURN_STATE_PRINT_CMD_LIST_OK;
}
/* run command handler with custom exit mechanism */
static int quit_run(const struct cat_command *cmd)
{
quit_flag = true;
return 0;
}
/* declaring print variables array */
static struct cat_variable print_vars[] = {
{
.type = CAT_VAR_UINT_DEC,
.data = &x,
.data_size = sizeof(x),
.name = "X",
.access = CAT_VAR_ACCESS_READ_WRITE,
},
{
.type = CAT_VAR_UINT_DEC,
.data = &y,
.data_size = sizeof(y),
.name = "Y",
.access = CAT_VAR_ACCESS_READ_WRITE,
},
{
.type = CAT_VAR_BUF_STRING,
.data = message,
.data_size = sizeof(message),
.name = "MESSAGE",
.access = CAT_VAR_ACCESS_READ_WRITE,
}
};
/* declaring commands array */
static struct cat_command cmds[] = {
{
.name = "+PRINT",
.description = "Printing something special at (X,Y).",
.run = print_run,
.var = print_vars,
.var_num = sizeof(print_vars) / sizeof(print_vars[0]),
.need_all_vars = true
},
{
.name = "#HELP",
.run = print_cmd_list,
},
{
.name = "#QUIT",
.run = quit_run
},
};
/* working buffer */
static char buf[128];
/* declaring parser descriptor */
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
/* custom target dependent input output handlers */
static int write_char(char ch)
{
putc(ch, stdout);
return 1;
}
static int read_char(char *ch)
{
*ch = getc(stdin);
return 1;
}
/* declaring input output interface descriptor for parser */
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
int main(int argc, char **argv)
{
struct cat_object at;
/* initializing */
cat_init(&at, &desc, &iface, NULL);
/* main loop with exit code conditions */
while ((cat_service(&at) != 0) && (quit_flag == 0)) {};
/* goodbye message */
printf("Bye!\n");
return 0;
}

View File

@@ -0,0 +1,260 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static int32_t speed;
static uint16_t adr;
static uint8_t x;
static uint8_t y;
static uint8_t bytes_buf[4];
static char msg[16];
static bool quit_flag;
static int x_write(const struct cat_variable *var, size_t write_size)
{
printf("x variable updated internally to: %u\n", x);
return 0;
}
static int y_write(const struct cat_variable *var, size_t write_size)
{
printf("y variable updated internally to: %u\n", y);
return 0;
}
static int msg_write(const struct cat_variable *var, size_t write_size)
{
printf("msg variable updated %lu bytes internally to: <%s>\n", write_size, msg);
return 0;
}
static int speed_write(const struct cat_variable *var, size_t write_size)
{
printf("speed variable updated internally to: %d\n", speed);
return 0;
}
static int adr_write(const struct cat_variable *var, size_t write_size)
{
printf("adr variable updated internally to: 0x%04X\n", adr);
return 0;
}
static int bytesbuf_write(const struct cat_variable *var, size_t write_size)
{
int i = 0;
printf("bytes_buf variable updated %lu bytes internally to: ", write_size);
for (i = 0; i < sizeof(bytes_buf); i++)
printf("%02X", bytes_buf[i]);
printf("\n");
return 0;
}
static int go_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
int i = 0;
printf("<%s>: x=%d y=%d msg=%s @ speed=%d\n",
cmd->name,
*(uint8_t*)(cmd->var[0].data),
*(uint8_t*)(cmd->var[1].data),
msg,
speed
);
printf("<bytes>: ");
for (i = 0; i < sizeof(bytes_buf); i++)
printf("%02X", bytes_buf[i]);
printf("\n");
return 0;
}
static int set_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
printf("<%s>: SET SPEED TO = %d\n",
cmd->name,
speed
);
return 0;
}
static int set_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
return 0;
}
static int test_run(const struct cat_command *cmd)
{
printf("TEST: <%s>", cmd->name);
return 0;
}
static int quit_run(const struct cat_command *cmd)
{
printf("QUIT: <%s>", cmd->name);
quit_flag = true;
return 0;
}
static int print_cmd_list(const struct cat_command *cmd)
{
return CAT_RETURN_STATE_PRINT_CMD_LIST_OK;
}
static struct cat_variable go_vars[] = {
{
.type = CAT_VAR_UINT_DEC,
.data = &x,
.data_size = sizeof(x),
.write = x_write,
.name = "x"
},
{
.type = CAT_VAR_UINT_DEC,
.data = &y,
.data_size = sizeof(y),
.write = y_write,
.name = "y"
},
{
.type = CAT_VAR_BUF_STRING,
.data = msg,
.data_size = sizeof(msg),
.write = msg_write,
.name = "msg"
}
};
static struct cat_variable set_vars[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &speed,
.data_size = sizeof(speed),
.write = speed_write,
.name = "speed"
},
{
.type = CAT_VAR_NUM_HEX,
.data = &adr,
.data_size = sizeof(adr),
.write = adr_write,
.name = "address"
},
{
.type = CAT_VAR_BUF_HEX,
.data = &bytes_buf,
.data_size = sizeof(bytes_buf),
.write = bytesbuf_write,
.name = "buffer"
}
};
static struct cat_command cmds[] = {
{
.name = "+GO",
.write = go_write,
.var = go_vars,
.var_num = sizeof(go_vars) / sizeof(go_vars[0]),
.need_all_vars = true
},
{
.name = "+SET",
.write = set_write,
.read = set_read,
.var = set_vars,
.var_num = sizeof(set_vars) / sizeof(set_vars[0]),
},
{
.name = "#TEST",
.run = test_run
},
{
.name = "#HELP",
.run = print_cmd_list,
},
{
.name = "#QUIT",
.run = quit_run
},
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
putc(ch, stdout);
return 1;
}
static int read_char(char *ch)
{
*ch = getc(stdin);
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
while ((cat_service(&at) != 0) && (quit_flag == 0)) {};
printf("Bye!\n");
return 0;
}

View File

@@ -0,0 +1,251 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
/* variables assigned to scan command */
static int rssi;
static char ssid[16];
/* helper variable used to exit demo code */
static bool quit_flag;
/* variables assigned to start command */
static int mode;
/* main at command parser object */
struct cat_object at;
struct scan_results {
int rssi;
char ssid[16];
};
/* static const scan results */
static const struct scan_results results[2][3] = {
{
{
.rssi = -10,
.ssid = "wifi1",
},
{
.rssi = -50,
.ssid = "wifi2",
},
{
.rssi = -20,
.ssid = "wifi3",
}
},
{
{
.rssi = -20,
.ssid = "bluetooth1",
}
}
};
/* helper variable */
static int scan_index;
/* run command handler with custom exit mechanism */
static int quit_run(const struct cat_command *cmd)
{
quit_flag = true;
return 0;
}
/* helper function */
static void load_scan_results(int index)
{
rssi = results[mode][index].rssi;
strcpy(ssid, results[mode][index].ssid);
}
/* declaring scan variables array */
static struct cat_variable scan_vars[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &rssi,
.data_size = sizeof(rssi),
.name = "RSSI"
},
{
.type = CAT_VAR_BUF_STRING,
.data = ssid,
.data_size = sizeof(ssid),
.name = "SSID"
}
};
/* forward declaration */
static cat_return_state scan_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size);
/* unsolicited command */
static struct cat_command scan_cmd = {
.name = "+SCAN",
.read = scan_read,
.var = scan_vars,
.var_num = sizeof(scan_vars) / sizeof(scan_vars[0])
};
/* unsolicited read callback handler */
static cat_return_state scan_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
int max = (mode == 0) ? 3 : 1;
scan_index++;
if (scan_index > max)
return CAT_RETURN_STATE_HOLD_EXIT_OK;
load_scan_results(scan_index);
cat_trigger_unsolicited_read(&at, &scan_cmd);
return CAT_RETURN_STATE_DATA_NEXT;
}
/* mode variable validator */
static int mode_write(const struct cat_variable *var, const size_t write_size)
{
if (*(int*)var->data >= 2)
return -1;
return 0;
}
/* start write callback handler */
static cat_return_state start_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
scan_index = 0;
load_scan_results(scan_index);
cat_trigger_unsolicited_read(&at, &scan_cmd);
return CAT_RETURN_STATE_HOLD;
}
/* run command handler attached to HELP command for printing commands list */
static int print_cmd_list(const struct cat_command *cmd)
{
return CAT_RETURN_STATE_PRINT_CMD_LIST_OK;
}
/* declaring start command variables array */
static struct cat_variable start_vars[] = {
{
.type = CAT_VAR_UINT_DEC,
.data = &mode,
.data_size = sizeof(mode),
.name = "MODE",
.write = mode_write,
.access = CAT_VAR_ACCESS_WRITE_ONLY,
}
};
/* declaring commands array */
static struct cat_command cmds[] = {
{
.name = "+START",
.description = "Start scanning after write (0 - wifi, 1 - bluetooth).",
.write = start_write,
.var = start_vars,
.var_num = sizeof(start_vars) / sizeof(start_vars[0]),
.need_all_vars = true
},
{
.name = "+SCAN",
.description = "Scan result record.",
.only_test = true,
.var = scan_vars,
.var_num = sizeof(scan_vars) / sizeof(scan_vars[0])
},
{
.name = "#HELP",
.run = print_cmd_list,
},
{
.name = "#QUIT",
.run = quit_run
},
};
/* working buffer */
static char buf[128];
/* declaring parser descriptor */
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
/* custom target dependent input output handlers */
static int write_char(char ch)
{
putc(ch, stdout);
return 1;
}
static int read_char(char *ch)
{
*ch = getc(stdin);
return 1;
}
/* declaring input output interface descriptor for parser */
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
int main(int argc, char **argv)
{
/* initializing */
cat_init(&at, &desc, &iface, NULL);
/* main loop with exit code conditions */
while ((cat_service(&at) != 0) && (quit_flag == 0)) {};
/* goodbye message */
printf("Bye!\n");
return 0;
}

2757
components/api/lib/cAT/src/cat.c Executable file

File diff suppressed because it is too large Load Diff

557
components/api/lib/cAT/src/cat.h Executable file
View File

@@ -0,0 +1,557 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef CAT_H
#define CAT_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stdio.h>
#include <stdbool.h>
/* only forward declarations (looks for definition below) */
struct cat_command;
struct cat_variable;
#ifndef CAT_UNSOLICITED_CMD_BUFFER_SIZE
/* unsolicited command buffer default size (can by override externally during compilation) */
#define CAT_UNSOLICITED_CMD_BUFFER_SIZE ((size_t)(1))
#endif
/* enum type with variable type definitions */
typedef enum {
CAT_VAR_INT_DEC = 0, /* decimal encoded signed integer variable */
CAT_VAR_UINT_DEC, /* decimal encoded unsigned integer variable */
CAT_VAR_NUM_HEX, /* hexadecimal encoded unsigned integer variable */
CAT_VAR_BUF_HEX, /* asciihex encoded bytes array */
CAT_VAR_BUF_STRING /* string variable */
} cat_var_type;
/* enum type wirh variable accessors definitions */
typedef enum {
CAT_VAR_ACCESS_READ_WRITE = 0, /* there will be possible to read and write variable */
CAT_VAR_ACCESS_READ_ONLY, /* there will be possible to read only variable */
CAT_VAR_ACCESS_WRITE_ONLY, /* there will be possible to write only variable */
} cat_var_access;
/* enum type with function status */
typedef enum {
CAT_STATUS_ERROR_BUFFER_EMPTY = -7,
CAT_STATUS_ERROR_NOT_HOLD = -6,
CAT_STATUS_ERROR_BUFFER_FULL = -5,
CAT_STATUS_ERROR_UNKNOWN_STATE = -4,
CAT_STATUS_ERROR_MUTEX_LOCK = -3,
CAT_STATUS_ERROR_MUTEX_UNLOCK = -2,
CAT_STATUS_ERROR = -1,
CAT_STATUS_OK = 0,
CAT_STATUS_BUSY = 1,
CAT_STATUS_HOLD = 2
} cat_status;
/**
* Write variable function handler
*
* This callback function is called after variable update immediatly.
* User application can validate writed value and check for amount of data size was written.
* This handler is optional, so when is not defined, operations will be fully automatically.
*
* @param var - pointer to struct descriptor of parsed variable
* @param write_size - size of data was written (useful especially with hexbuf var type)
* @return 0 - ok, else error and stop parsing
* */
typedef int (*cat_var_write_handler)(const struct cat_variable *var, const size_t write_size);
/**
* Read variable function handler
*
* This callback function is called just before variable value read.
* User application can copy data from private fields to variable connected with parsed command.
* This handler is optional, so when is not defined, operations will be fully automatically.
*
* @param var - pointer to struct descriptor of parsed variable
* @return 0 - ok, else error and stop parsing
* */
typedef int (*cat_var_read_handler)(const struct cat_variable *var);
/**
* Write variable extended function handler
*
* This callback function is called after variable update immediatly.
* User application can validate writed value and check for amount of data size was written.
* This handler is optional, so when is not defined, operations will be fully automatically.
*
* @param var - pointer to struct descriptor of parsed variable
* @param cmd - pointer to variable parent command structure
* @param write_size - size of data was written (useful especially with hexbuf var type)
* @return 0 - ok, else error and stop parsing
* */
typedef int (*cat_var_write_ex_handler)(const struct cat_variable *var, const struct cat_command *cmd, const size_t write_size);
/**
* Read variable function handler
*
* This callback function is called just before variable value read.
* User application can copy data from private fields to variable connected with parsed command.
* This handler is optional, so when is not defined, operations will be fully automatically.
*
* @param var - pointer to struct descriptor of parsed variable
* @param cmd - pointer to variable parent command structure
* @return 0 - ok, else error and stop parsing
* */
typedef int (*cat_var_read_ex_handler)(const struct cat_variable *var, const struct cat_command *cmd);
/**
* Data getter for variable.
* The purpose of this function is to replace statically allocated data and data_size fields
* with function pointer with context. Then the data and data_size from this getter would be
* changed and returned runtime.
*
* @param var - pointer to struct descriptor of parsed variable
* @param context - command context
* @param size - pointer to variable where should be placed data size
* @return pointer to data array from context
*/
typedef void* (*cat_var_data_getter)(const struct cat_variable *var, void *context, size_t *data_size);
struct cat_variable {
const char *name; /* variable name (optional - using only for auto format test command response) */
cat_var_type type; /* variable type (needed for parsing and validating) */
void *data; /* generic pointer to statically allocated memory for variable data read/write/validate operations */
size_t data_size; /* variable data size, pointed by data pointer */
cat_var_access access; /* variable accessor */
cat_var_write_handler write; /* write variable handler */
cat_var_read_handler read; /* read variable handler */
cat_var_write_ex_handler write_ex; /* optional write variable extended handler */
cat_var_read_ex_handler read_ex; /* optional read variable extended handler */
cat_var_data_getter data_getter; /* optional data getter for dynamic linking data and data_size */
};
/* enum type with command callbacks return values meaning */
typedef enum {
CAT_RETURN_STATE_ERROR = -1, /* immediatly error acknowledge */
CAT_RETURN_STATE_DATA_OK, /* send current data buffer followed by ok acknowledge */
CAT_RETURN_STATE_DATA_NEXT, /* send current data buffer and go to next callback iteration */
CAT_RETURN_STATE_NEXT, /* go to next callback iteration without sending anything */
CAT_RETURN_STATE_OK, /* immediatly ok acknowledge */
CAT_RETURN_STATE_HOLD, /* enable hold parser state */
CAT_RETURN_STATE_HOLD_EXIT_OK, /* exit from hold state with OK response */
CAT_RETURN_STATE_HOLD_EXIT_ERROR, /* exit from hold state with ERROR response */
CAT_RETURN_STATE_PRINT_CMD_LIST_OK, /* print commands list followed by ok acknowledge (only in TEST and RUN) */
} cat_return_state;
/**
* Write command function handler (AT+CMD=)
*
* This callback function is called after parsing all connected variables.
* User application can validate all variales at once at this moment, or copy them to the other application layer buffer.
* User can check number of variables or make custom process of parsing non standard arguments format.
* This handler is optional, so when is not defined, operations on variables will be fully automatically.
* If neither write handler nor variables not defined, then write command type is not available.
*
* @param cmd - pointer to struct descriptor of processed command
* @param data - pointer to arguments buffer for custom parsing
* @param data_size - length of arguments buffer
* @param args_num - number of passed arguments connected to variables
* @return according to cat_return_state enum definitions
* */
typedef cat_return_state (*cat_cmd_write_handler)(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num);
/**
* Read command function handler (AT+CMD?)
*
* This callback function is called after format all connected variables.
* User application can change automatic response, or add some custom data to response.
* This handler is optional, so when is not defined, operations on variables will be fully automatically.
* If neither read handler nor variables not defined, then read command type is not available.
*
* @param cmd - pointer to struct descriptor of processed command
* @param data - pointer to arguments buffer for custom parsing
* @param data_size - pointer to length of arguments buffer (can be modifed if needed)
* @param max_data_size - maximum length of buffer pointed by data pointer
* @return according to cat_return_state enum definitions
* */
typedef cat_return_state (*cat_cmd_read_handler)(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size);
/**
* Run command function handler (AT+CMD)
*
* No operations on variables are done.
* This handler is optional.
* If run handler not defined, then run command type is not available.
*
* @param cmd - pointer to struct descriptor of processed command
* @return according to cat_return_state enum definitions
* */
typedef cat_return_state (*cat_cmd_run_handler)(const struct cat_command *cmd);
/**
* Test command function handler (AT+CMD=?)
*
* This callback function is called after format all connected variables.
* User application can change automatic response, or add some custom data to response.
* This handler is optional, so when is not defined, operations on variables will be fully automatically.
* If neither test handler nor variables not defined, then test command type is not available.
* Exception of this rule is write command without variables.
* In this case, the "question mark" will be passed as a custom argument to the write handler.
*
* @param cmd - pointer to struct descriptor of processed command
* @param data - pointer to arguments buffer for custom parsing
* @param data_size - pointer to length of arguments buffer (can be modifed if needed)
* @param max_data_size - maximum length of buffer pointed by data pointer
* @return according to cat_return_state enum definitions
* */
typedef cat_return_state (*cat_cmd_test_handler)(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size);
/* enum type with main at parser fsm state */
typedef enum {
CAT_STATE_ERROR = -1,
CAT_STATE_IDLE,
CAT_STATE_PARSE_PREFIX,
CAT_STATE_PARSE_COMMAND_CHAR,
CAT_STATE_UPDATE_COMMAND_STATE,
CAT_STATE_WAIT_READ_ACKNOWLEDGE,
CAT_STATE_SEARCH_COMMAND,
CAT_STATE_COMMAND_FOUND,
CAT_STATE_COMMAND_NOT_FOUND,
CAT_STATE_PARSE_COMMAND_ARGS,
CAT_STATE_PARSE_WRITE_ARGS,
CAT_STATE_FORMAT_READ_ARGS,
CAT_STATE_WAIT_TEST_ACKNOWLEDGE,
CAT_STATE_FORMAT_TEST_ARGS,
CAT_STATE_WRITE_LOOP,
CAT_STATE_READ_LOOP,
CAT_STATE_TEST_LOOP,
CAT_STATE_RUN_LOOP,
CAT_STATE_HOLD,
CAT_STATE_FLUSH_IO_WRITE_WAIT,
CAT_STATE_FLUSH_IO_WRITE,
CAT_STATE_AFTER_FLUSH_RESET,
CAT_STATE_AFTER_FLUSH_OK,
CAT_STATE_AFTER_FLUSH_FORMAT_READ_ARGS,
CAT_STATE_AFTER_FLUSH_FORMAT_TEST_ARGS,
CAT_STATE_PRINT_CMD,
} cat_state;
/* enum type with type of command request */
typedef enum {
CAT_CMD_TYPE_NONE = -1,
CAT_CMD_TYPE_RUN,
CAT_CMD_TYPE_READ,
CAT_CMD_TYPE_WRITE,
CAT_CMD_TYPE_TEST,
CAT_CMD_TYPE__TOTAL_NUM
} cat_cmd_type;
/* structure with io interface functions */
struct cat_io_interface {
int (*write)(char ch); /* write char to output stream. return 1 if byte wrote successfully. */
int (*read)(char *ch); /* read char from input stream. return 1 if byte read successfully. */
};
/* structure with mutex interface functions */
struct cat_mutex_interface {
int (*lock)(void); /* lock mutex handler. return 0 if successfully locked, otherwise - cannot lock */
int (*unlock)(void); /* unlock mutex handler. return 0 if successfully unlocked, otherwise - cannot unlock */
};
/* structure with at command descriptor */
struct cat_command {
const char *name; /* at command name (case-insensitivity) */
const char *description; /* at command description (optionally - can be null) */
cat_cmd_write_handler write; /* write command handler */
cat_cmd_read_handler read; /* read command handler */
cat_cmd_run_handler run; /* run command handler */
cat_cmd_test_handler test; /* test command handler */
struct cat_variable const *var; /* pointer to array of variables assiocated with this command */
size_t var_num; /* number of variables in array */
bool need_all_vars; /* flag to need all vars parsing */
bool only_test; /* flag to disable read/write/run commands (only test auto description) */
bool disable; /* flag to completely disable command */
void* context; /* pointer to optional context structure */
};
struct cat_command_group {
const char *name; /* command group name (optional, for identification purpose) */
struct cat_command const *cmd; /* pointer to array of commands descriptor */
size_t cmd_num; /* number of commands in array */
bool disable; /* flag to completely disable all commands in group */
};
/* structure with at command parser descriptor */
struct cat_descriptor {
struct cat_command_group* const *cmd_group; /* pointer to array of commands group descriptor */
size_t cmd_group_num; /* number of commands group in array */
uint8_t *buf; /* pointer to working buffer (used to parse command argument) */
size_t buf_size; /* working buffer length */
/* optional unsolicited buffer, if not configured (NULL) */
/* then the buf will be divided into two smaller buffers */
uint8_t *unsolicited_buf; /* pointer to unsolicited working buffer (used to parse command argument) */
size_t unsolicited_buf_size; /* unsolicited working buffer length */
};
/* strcuture with unsolicited command buffered infos */
struct cat_unsolicited_cmd {
struct cat_command const *cmd; /* pointer to commands used to unsolicited event */
cat_cmd_type type; /* type of unsolicited event */
};
/* enum type with unsolicited events fsm state */
typedef enum {
CAT_UNSOLICITED_STATE_IDLE,
CAT_UNSOLICITED_STATE_FORMAT_READ_ARGS,
CAT_UNSOLICITED_STATE_FORMAT_TEST_ARGS,
CAT_UNSOLICITED_STATE_READ_LOOP,
CAT_UNSOLICITED_STATE_TEST_LOOP,
CAT_UNSOLICITED_STATE_FLUSH_IO_WRITE_WAIT,
CAT_UNSOLICITED_STATE_FLUSH_IO_WRITE,
CAT_UNSOLICITED_STATE_AFTER_FLUSH_RESET,
CAT_UNSOLICITED_STATE_AFTER_FLUSH_OK,
CAT_UNSOLICITED_STATE_AFTER_FLUSH_FORMAT_READ_ARGS,
CAT_UNSOLICITED_STATE_AFTER_FLUSH_FORMAT_TEST_ARGS,
} cat_unsolicited_state;
/* enum type with fsm type */
typedef enum {
CAT_FSM_TYPE_ATCMD,
CAT_FSM_TYPE_UNSOLICITED,
CAT_FSM_TYPE__TOTAL_NUM,
} cat_fsm_type;
struct cat_unsolicited_fsm {
cat_unsolicited_state state; /* current unsolicited fsm state */
size_t index; /* index used to iterate over commands and variables */
size_t position; /* position of actually parsed char in arguments string */
struct cat_command const *cmd; /* pointer to current command descriptor */
struct cat_variable const *var; /* pointer to current variable descriptor */
cat_cmd_type cmd_type; /* type of command request */
char const *write_buf; /* working buffer pointer used for asynch writing to io */
int write_state; /* before, data, after flush io write state */
cat_unsolicited_state write_state_after; /* parser state to set after flush io write */
struct cat_unsolicited_cmd unsolicited_cmd_buffer[CAT_UNSOLICITED_CMD_BUFFER_SIZE]; /* buffer with unsolicited commands used to unsolicited event */
size_t unsolicited_cmd_buffer_tail; /* tail index of unsolicited cmd buffer */
size_t unsolicited_cmd_buffer_head; /* head index of unsolicited cmd buffer */
size_t unsolicited_cmd_buffer_items_count; /* number of unsolicited cmd in buffer */
};
/* structure with main at command parser object */
struct cat_object {
struct cat_descriptor const *desc; /* pointer to at command parser descriptor */
struct cat_io_interface const *io; /* pointer to at command parser io interface */
struct cat_mutex_interface const *mutex; /* pointer to at command parser mutex interface */
size_t index; /* index used to iterate over commands and variables */
size_t partial_cntr; /* partial match commands counter */
size_t length; /* length of input command name and command arguments */
size_t position; /* position of actually parsed char in arguments string */
size_t write_size; /* size of parsed buffer hex or buffer string */
size_t commands_num; /* computed total number of registered commands */
struct cat_command const *cmd; /* pointer to current command descriptor */
struct cat_variable const *var; /* pointer to current variable descriptor */
cat_cmd_type cmd_type; /* type of command request */
char current_char; /* current received char from input stream */
cat_state state; /* current fsm state */
bool cr_flag; /* flag for detect <cr> char in input string */
bool hold_state_flag; /* status of hold state (independent from fsm states) */
int hold_exit_status; /* hold exit parameter with status */
char const *write_buf; /* working buffer pointer used for asynch writing to io */
int write_state; /* before, data, after flush io write state */
cat_state write_state_after; /* parser state to set after flush io write */
struct cat_unsolicited_fsm unsolicited_fsm;
};
/**
* Function used to initialize at command parser.
* Initialize starting values of object fields.
*
* @param self pointer to at command parser object to initialize
* @param desc pointer to at command parser descriptor
* @param io pointer to at command parser io low-level layer interface
* @param mutex pointer to at command partes mutex interface
*/
void cat_init(struct cat_object *self, const struct cat_descriptor *desc, const struct cat_io_interface *io, const struct cat_mutex_interface *mutex);
/**
* Function must be called periodically to asynchronoulsy run at command parser.
* Commands handlers will be call from this function context.
*
* @param self pointer to at command parser object
* @return according to cat_return_state enum definitions
*/
cat_status cat_service(struct cat_object *self);
/**
* Function return flag which indicating internal busy state.
* It is used to determine whether external application modules can use shared input / output interfaces functions.
* It is usefull especially in rtos environments.
* If internal parser state is busy by doing some processing then function return 1.
* If the function returns 0, then the external application modules can safely use the input / output interfaces functions shared with the library.
* If the function returns 1, then input / output interface function are used by internal parser functions.
*
* @param self pointer to at command parser object
* @return according to cat_return_state enum definitions
*/
cat_status cat_is_busy(struct cat_object *self);
/**
* Function return flag which indicating parsing hold state.
* If the function returns 0, then the at parsing process is normal.
* If the function returns 1, then the at parsing process is holded.
* To exit from hold state, user have to call cat_hold_exit or return HOLD_EXIT return value in callback.
*
* @param self pointer to at command parser object
* @return according to cat_return_state enum definitions
*/
cat_status cat_is_hold(struct cat_object *self);
/**
* Function return flag which indicating state of internal buffer of unsolicited events.
*
* @param self pointer to at command parser object
* @return CAT_STATUS_OK - buffer is not full, unsolicited event can be buffered
* CAT_STATUS_ERROR_BUFFER_FULL - buffer is full, unsolicited event cannot be buffered
* CAT_STATUS_ERROR_MUTEX_LOCK - cannot lock mutex error
* CAT_STATUS_ERROR_MUTEX_UNLOCK - cannot unlock mutex error
*/
cat_status cat_is_unsolicited_buffer_full(struct cat_object *self);
/**
* Function sends unsolicited event message.
* Command message is buffered inside parser in 1-level deep buffer and processed in cat_service context.
* Only command pointer is buffered, so command struct should be static or global until be fully processed.
*
* @param self pointer to at command parser object
* @param cmd pointer to command structure regarding which unsolicited event applies to
* @param type type of operation (only CAT_CMD_TYPE_READ and CAT_CMD_TYPE_TEST are allowed)
* @return according to cat_return_state enum definitions
*/
cat_status cat_trigger_unsolicited_event(struct cat_object *self, struct cat_command const *cmd, cat_cmd_type type);
/**
* Function sends unsolicited read event message.
* Command message is buffered inside parser in 1-level deep buffer and processed in cat_service context.
* Only command pointer is buffered, so command struct should be static or global until be fully processed.
*
* @param self pointer to at command parser object
* @param cmd pointer to command structure regarding which unsolicited read applies to
* @return according to cat_return_state enum definitions
*/
cat_status cat_trigger_unsolicited_read(struct cat_object *self, struct cat_command const *cmd);
/**
* Function sends unsolicited test event message.
* Command message is buffered inside parser in 1-level deep buffer and processed in cat_service context.
* Only command pointer is buffered, so command struct should be static or global until be fully processed.
*
* @param self pointer to at command parser object
* @param cmd pointer to command structure regarding which unsolicited test applies to
* @return according to cat_return_state enum definitions
*/
cat_status cat_trigger_unsolicited_test(struct cat_object *self, struct cat_command const *cmd);
/**
* Function used to exit from hold state with OK/ERROR response and back to idle state.
*
* @param self pointer to at command parser object
* @param status response status 0 - OK, else ERROR
* @return according to cat_return_state enum definitions
*/
cat_status cat_hold_exit(struct cat_object *self, cat_status status);
/**
* Function used to searching registered command by its name.
*
* @param self pointer to at command parser object
* @param name command name to search
* @return pointer to command object, NULL if command not found
*/
struct cat_command const* cat_search_command_by_name(struct cat_object *self, const char *name);
/**
* Function used to searching registered command group by its name.
*
* @param self pointer to at command parser object
* @param name command group name to search
* @return pointer to command group object, NULL if command group not found
*/
struct cat_command_group const* cat_search_command_group_by_name(struct cat_object *self, const char *name);
/**
* Function used to searching attached variable to command its name.
*
* @param self pointer to at command parser object
* @param cmd pointer to command in which variable will be searched
* @param name variable name to search
* @return pointer to command group object, NULL if command group not found
*/
struct cat_variable const* cat_search_variable_by_name(struct cat_object *self, struct cat_command const *cmd, const char *name);
/**
* Function used to check what command is currently processed.
* Function is not protected by mutex mechanism, due to processed cmd may change after function return.
* This only matters in multithreaded environments, it does not matter for one thread.
*
* @param self pointer to at command parser object
* @param fsm type of internal state machine to check current command
* @return pointer to command which is currently processed, NULL if no command is processed
*/
struct cat_command const* cat_get_processed_command(struct cat_object *self, cat_fsm_type fsm);
/**
* Function return unsolicited event command status.
* Function is not protected by mutex mechanism, due to processed cmd may change after function return.
* This only matters in multithreaded environments, it does not matter for one thread.
*
* @param self pointer to at command parser object
* @param cmd pointer to command in which variable will be searched
* @param type type of unsolicited event
* @return CAT_STATUS_OK - command is not buffered nor processed
* CAT_STATUS_BUSY - command is waiting in buffer or is processed
*/
cat_status cat_is_unsolicited_event_buffered(struct cat_object *self, struct cat_command const *cmd, cat_cmd_type type);
#ifdef __cplusplus
}
#endif
#endif /* CAT_H */

View File

@@ -0,0 +1,340 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char ack_results[512];
static int8_t var1;
static int8_t var2;
static char const *input_text;
static size_t input_index;
static int cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
return 0;
}
static int cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
return 0;
}
static int cmd_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
return 0;
}
static int cmd_run(const struct cat_command *cmd)
{
return 0;
}
static int var1_write(const struct cat_variable *var, size_t write_size)
{
return 0;
}
static int var2_write(const struct cat_variable *var, size_t write_size)
{
return 0;
}
static int print_cmd_list(const struct cat_command *cmd)
{
return CAT_RETURN_STATE_PRINT_CMD_LIST_OK;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write
}
};
static struct cat_variable vars_ro[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write,
.access = CAT_VAR_ACCESS_READ_ONLY
}
};
static struct cat_variable vars_wo[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write,
.access = CAT_VAR_ACCESS_WRITE_ONLY
}
};
static struct cat_variable vars2[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write
},
{
.type = CAT_VAR_INT_DEC,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write
}
};
static struct cat_variable vars2_ro[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write,
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write
}
};
static struct cat_variable vars2_wo[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write,
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write
}
};
static struct cat_command cmds[] = {
{
.name = "+V1",
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+V1RO",
.var = vars_ro,
.var_num = sizeof(vars_ro) / sizeof(vars_ro[0])
},
{
.name = "+V1RW",
.var = vars_wo,
.var_num = sizeof(vars_wo) / sizeof(vars_wo[0])
},
{
.name = "+V11",
.var = vars2,
.var_num = sizeof(vars2) / sizeof(vars2[0])
},
{
.name = "+V11RO",
.var = vars2_ro,
.var_num = sizeof(vars2_ro) / sizeof(vars2_ro[0])
},
{
.name = "+V11WO",
.var = vars2_wo,
.var_num = sizeof(vars2_wo) / sizeof(vars2_wo[0])
},
{
.name = "+V2",
.write = cmd_write,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+V3",
.write = cmd_write,
.read = cmd_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+V4",
.write = cmd_write,
.read = cmd_read,
.test = cmd_test,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+V5",
.write = cmd_write,
.read = cmd_read,
.test = cmd_test,
.run = cmd_run,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+S1",
},
{
.name = "+S2",
.write = cmd_write,
},
{
.name = "+S3",
.write = cmd_write,
.read = cmd_read,
},
{
.name = "+S4",
.write = cmd_write,
.read = cmd_read,
.test = cmd_test,
},
{
.name = "+S5",
.write = cmd_write,
.read = cmd_read,
.test = cmd_test,
.run = cmd_run,
},
{
.name = "+D1",
.write = cmd_write,
.read = cmd_read,
.test = cmd_test,
.run = cmd_run,
.disable = true,
},
{
.name = "+T1",
.write = cmd_write,
.read = cmd_read,
.test = cmd_test,
.run = cmd_run,
.only_test = true,
},
{
.name = "+T2",
.only_test = true,
},
{
.name = "#HELP",
.run = print_cmd_list,
}
};
static char buf[512];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(ack_results, 0, sizeof(ack_results));
}
static void print_raw_text(char *p)
{
while (*p != '\0') {
if (*p == '\n') {
printf("\\n");
} else {
putchar(*p);
}
p++;
}
}
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input("\nAT#HELP\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nAT+V1?\nAT+V1=\nAT+V1=?\n\nAT+V1RO?\nAT+V1RO=?\n\nAT+V1RW=\nAT+V1RW=?\n\nAT+V11?\nAT+V11=\nAT+V11=?\n\nAT+V11RO?\nAT+V11RO=\nAT+V11RO=?\n\nAT+V11WO?\nAT+V11WO=\nAT+V11WO=?\n\nAT+V2?\nAT+V2=\nAT+V2=?\n\nAT+V3?\nAT+V3=\nAT+V3=?\n\nAT+V4?\nAT+V4=\nAT+V4=?\n\nAT+V5\nAT+V5?\nAT+V5=\nAT+V5=?\n\nAT+S2=\n\nAT+S3?\nAT+S3=\n\nAT+S4?\nAT+S4=\nAT+S4=?\n\nAT+S5\nAT+S5?\nAT+S5=\nAT+S5=?\n\nAT+T1=?\n\nAT#HELP\n\nOK\n") == 0);
return 0;
}

View File

@@ -0,0 +1,229 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char cmd_results[256];
static char var_read_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x, var_u1, var_u2;
static struct cat_object at;
static struct cat_command u_cmds[];
static cat_return_state cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
cat_status s;
strcat(cmd_results, " write:");
strcat(cmd_results, cmd->name);
if (var_x < 2) {
s = cat_trigger_unsolicited_read(&at, &u_cmds[var_x]);
assert(s == CAT_STATUS_OK);
return CAT_RETURN_STATE_HOLD;
}
return CAT_RETURN_STATE_ERROR;
}
static cat_return_state cmd1_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
cat_status s;
strcat(cmd_results, " read1:");
strcat(cmd_results, cmd->name);
if (var_u1 > 0) {
var_u1--;
s = cat_trigger_unsolicited_read(&at, cmd);
assert(s == CAT_STATUS_OK);
return CAT_RETURN_STATE_DATA_OK;
}
return CAT_RETURN_STATE_HOLD_EXIT_OK;
}
static cat_return_state cmd2_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
cat_status s;
strcat(cmd_results, " read2:");
strcat(cmd_results, cmd->name);
if (var_u2 > 0) {
var_u2--;
s = cat_trigger_unsolicited_read(&at, cmd);
assert(s == CAT_STATUS_OK);
return CAT_RETURN_STATE_DATA_OK;
}
cat_hold_exit(&at, CAT_STATUS_OK);
return CAT_RETURN_STATE_DATA_OK;
}
static int var_read(const struct cat_variable *var)
{
strcat(var_read_results, " var_read:");
strcat(var_read_results, var->name);
return 0;
}
static struct cat_variable u_vars[] = {
{
.name = "U1",
.type = CAT_VAR_INT_DEC,
.data = &var_u1,
.data_size = sizeof(var_u1),
.read = var_read
},
{
.name = "U2",
.type = CAT_VAR_INT_DEC,
.data = &var_u2,
.data_size = sizeof(var_u2),
.read = var_read
}
};
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x),
.read = var_read
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.write = cmd_write,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static struct cat_command u_cmds[] = {
{
.name = "+U1CMD",
.read = cmd1_read,
.var = &u_vars[0],
.var_num = 1,
},
{
.name = "+U2CMD",
.read = cmd2_read,
.var = &u_vars[1],
.var_num = 1,
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_u1 = 2;
var_u2 = 3;
memset(ack_results, 0, sizeof(ack_results));
memset(cmd_results, 0, sizeof(cmd_results));
memset(var_read_results, 0, sizeof(var_read_results));
}
static const char test_case_1[] = "\nAT+CMD=0\n\nAT+CMD=1\n";
int main(int argc, char **argv)
{
cat_status s;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+U1CMD=2\n\n+U1CMD=1\n\nOK\n\n+U2CMD=3\n\n+U2CMD=2\n\n+U2CMD=1\n\n+U2CMD=0\n\nOK\n") == 0);
assert(strcmp(cmd_results, " write:+CMD read1:+U1CMD read1:+U1CMD read1:+U1CMD write:+CMD read2:+U2CMD read2:+U2CMD read2:+U2CMD read2:+U2CMD") == 0);
assert(strcmp(var_read_results, " var_read:U1 var_read:U1 var_read:U1 var_read:U2 var_read:U2 var_read:U2 var_read:U2") == 0);
return 0;
}

View File

@@ -0,0 +1,185 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char run_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int a_run(const struct cat_command *cmd)
{
strcat(run_results, " A:");
strcat(run_results, cmd->name);
return 0;
}
static int ap_run(const struct cat_command *cmd)
{
strcat(run_results, " AP:");
strcat(run_results, cmd->name);
return 0;
}
static int test_run(const struct cat_command *cmd)
{
strcat(run_results, " +TEST:");
strcat(run_results, cmd->name);
return 0;
}
static struct cat_command cmds[] = {
{
.name = "A",
.run = a_run
},
{
.name = "AP",
.run = ap_run
},
{
.name = "+TEST",
.run = test_run
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static int mutex_ret_lock;
static int mutex_ret_unlock;
static int mutex_lock(void)
{
return mutex_ret_lock;
}
static int mutex_unlock(void)
{
return mutex_ret_unlock;
}
static struct cat_mutex_interface mutex = {
.lock = mutex_lock,
.unlock = mutex_unlock
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
mutex_ret_lock = 0;
mutex_ret_unlock = 0;
memset(run_results, 0, sizeof(run_results));
memset(ack_results, 0, sizeof(ack_results));
}
static const char test_case_1[] = "\nAT\nAT+test\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, &mutex);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nOK\n") == 0);
assert(strcmp(run_results, " +TEST:+TEST") == 0);
mutex_ret_lock = 1;
mutex_ret_unlock = 0;
assert(cat_service(&at) == CAT_STATUS_ERROR_MUTEX_LOCK);
mutex_ret_lock = 0;
mutex_ret_unlock = 1;
assert(cat_service(&at) == CAT_STATUS_ERROR_MUTEX_UNLOCK);
mutex_ret_lock = 1;
mutex_ret_unlock = 0;
assert(cat_is_busy(&at) == CAT_STATUS_ERROR_MUTEX_LOCK);
mutex_ret_lock = 0;
mutex_ret_unlock = 1;
assert(cat_is_busy(&at) == CAT_STATUS_ERROR_MUTEX_UNLOCK);
mutex_ret_lock = 0;
mutex_ret_unlock = 0;
assert(cat_service(&at) == CAT_STATUS_OK);
assert(cat_is_busy(&at) == CAT_STATUS_OK);
return 0;
}

View File

@@ -0,0 +1,223 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char run_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int e_run(const struct cat_command *cmd)
{
strcat(run_results, " E:");
strcat(run_results, cmd->name);
return 0;
}
static int e0_run(const struct cat_command *cmd)
{
strcat(run_results, " E0:");
strcat(run_results, cmd->name);
return 0;
}
static int e1_run(const struct cat_command *cmd)
{
strcat(run_results, " E1:");
strcat(run_results, cmd->name);
return 0;
}
static struct cat_command cmds1[] = {
{
.name = "E",
.run = e_run,
},
{
.name = "E0",
.run = e0_run,
},
{
.name = "E1",
.run = e1_run,
}
};
static struct cat_command cmds2[] = {
{
.name = "E0",
.run = e0_run,
},
{
.name = "E1",
.run = e1_run,
},
{
.name = "E",
.run = e_run,
}
};
static struct cat_command cmds3[] = {
{
.name = "E0",
.run = e0_run,
},
{
.name = "E",
.run = e_run,
},
{
.name = "E1",
.run = e1_run,
}
};
static char buf[128];
static struct cat_command_group cmd_1_group = {
.cmd = cmds1,
.cmd_num = sizeof(cmds1) / sizeof(cmds1[0]),
};
static struct cat_command_group *cmd_1_desc[] = {
&cmd_1_group
};
static struct cat_descriptor desc_1 = {
.cmd_group = cmd_1_desc,
.cmd_group_num = sizeof(cmd_1_desc) / sizeof(cmd_1_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static struct cat_command_group cmd_2_group = {
.cmd = cmds2,
.cmd_num = sizeof(cmds2) / sizeof(cmds2[0]),
};
static struct cat_command_group *cmd_2_desc[] = {
&cmd_2_group
};
static struct cat_descriptor desc_2 = {
.cmd_group = cmd_2_desc,
.cmd_group_num = sizeof(cmd_2_desc) / sizeof(cmd_2_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static struct cat_command_group cmd_3_group = {
.cmd = cmds3,
.cmd_num = sizeof(cmds3) / sizeof(cmds3[0]),
};
static struct cat_command_group *cmd_3_desc[] = {
&cmd_3_group
};
static struct cat_descriptor desc_3 = {
.cmd_group = cmd_3_desc,
.cmd_group_num = sizeof(cmd_3_desc) / sizeof(cmd_3_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(run_results, 0, sizeof(run_results));
memset(ack_results, 0, sizeof(ack_results));
}
static const char test_case_1[] = "\nATE\n\nATE0\n\nATE1\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc_1, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nOK\n\nOK\n") == 0);
assert(strcmp(run_results, " E:E E0:E0 E1:E1") == 0);
cat_init(&at, &desc_2, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nOK\n\nOK\n") == 0);
assert(strcmp(run_results, " E:E E0:E0 E1:E1") == 0);
cat_init(&at, &desc_3, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nOK\n\nOK\n") == 0);
assert(strcmp(run_results, " E:E E0:E0 E1:E1") == 0);
return 0;
}

View File

@@ -0,0 +1,195 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char run_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int a_run(const struct cat_command *cmd)
{
strcat(run_results, " A:");
strcat(run_results, cmd->name);
return 0;
}
static int ap_run(const struct cat_command *cmd)
{
strcat(run_results, " AP:");
strcat(run_results, cmd->name);
return 0;
}
static int test_run(const struct cat_command *cmd)
{
strcat(run_results, " +TEST:");
strcat(run_results, cmd->name);
return 0;
}
static struct cat_command cmds[] = {
{
.name = "A",
.run = a_run,
.disable = false,
},
{
.name = "AP",
.run = ap_run,
.disable = false,
},
{
.name = "+TEST",
.run = test_run,
.disable = false,
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(run_results, 0, sizeof(run_results));
memset(ack_results, 0, sizeof(ack_results));
}
static const char test_case_1[] = "\nsa\rAT\n\r\nAT\nAT+\n\nATA\r\natap\naaaattttap\na\n\r+test\r\n+testATA\nATAPATAP\n\rAT\rATA\nAT+test\r\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\r\nERROR\r\n\nOK\n\nOK\n\r\nOK\r\n\nOK\n\nERROR\n\nERROR\n\r\nERROR\r\n\nERROR\n\nERROR\n\r\nERROR\r\n\r\nOK\r\n") == 0);
assert(strcmp(run_results, " +TEST:+TEST A:A AP:AP +TEST:+TEST") == 0);
prepare_input("\nAT\n");
while (cat_service(&at) != 0) {};
assert(cat_is_busy(&at) == 0);
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(run_results, "") == 0);
prepare_input("\nAT+te");
while (cat_service(&at) != 0) {};
assert(cat_is_busy(&at) != 0);
assert(strcmp(ack_results, "") == 0);
assert(strcmp(run_results, "") == 0);
prepare_input("st\n");
while (cat_service(&at) != 0) {};
assert(cat_is_busy(&at) == 0);
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(run_results, " +TEST:+TEST") == 0);
struct cat_command *cmd;
cmd = (struct cat_command*)cat_search_command_by_name(&at, "A");
cmd->disable = true;
cmd = (struct cat_command*)cat_search_command_by_name(&at, "+TEST");
cmd->disable = true;
prepare_input("\nATA\n\nATAP\n\nAT+TEST\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(run_results, " AP:AP AP:AP") == 0);
struct cat_command_group *cmd_group;
cmd_group = (struct cat_command_group*)cat_search_command_group_by_name(&at, "standard");
assert(cmd_group == NULL);
cmd_desc[0]->name = "standard";
cmd_group = (struct cat_command_group*)cat_search_command_group_by_name(&at, "standard");
assert(cmd_group == cmd_desc[0]);
cmd_group->disable = true;
prepare_input("\nATA\n\nATAP\n\nAT+TEST\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nERROR\n\nERROR\n") == 0);
assert(strcmp(run_results, "") == 0);
return 0;
}

View File

@@ -0,0 +1,165 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char run_results[256];
static char read_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int a_run(const struct cat_command *cmd)
{
strcat(run_results, " A_");
strcat(run_results, cmd->name);
return 0;
}
static int a_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(read_results, " A:");
strcat(read_results, cmd->name);
snprintf(data, max_data_size, "%s=A-val", cmd->name);
*data_size = strlen(data);
return 0;
}
static int ap_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(read_results, " AP:");
strcat(read_results, cmd->name);
*data_size = 0;
return 0;
}
static int test_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(read_results, " +TEST:");
strcat(read_results, cmd->name);
return -1;
}
static struct cat_command cmds[] = {
{
.name = "A",
.read = a_read,
.run = a_run
},
{
.name = "AP",
.read = ap_read
},
{
.name = "+TEST",
.read = test_read
},
{
.name = "+EMPTY"
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(run_results, 0, sizeof(run_results));
memset(ack_results, 0, sizeof(ack_results));
memset(read_results, 0, sizeof(read_results));
}
static const char test_case_1[] = "\nAT\r\nAT+\nAT+?\nATA?\r\nATAP\nATAP?\nATAPA?\nAT+TEST?\nAT+te?\nAT+e?\nAT+empTY?\r\nATA\r\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\r\nOK\r\n\nERROR\n\nERROR\n\r\nA=A-val\r\n\r\nOK\r\n\nERROR\n\nAP=\n\nOK\n\nERROR\n\nERROR\n\nERROR\n\nERROR\n\r\nERROR\r\n\r\nOK\r\n") == 0);
assert(strcmp(run_results, " A_A") == 0);
assert(strcmp(read_results, " A:A AP:AP +TEST:+TEST +TEST:+TEST") == 0);
return 0;
}

View File

@@ -0,0 +1,225 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char ack_results[256];
static int8_t var_int;
static uint8_t var_uint;
static uint8_t var_hex8;
static uint16_t var_hex16;
static uint32_t var_hex32;
static uint8_t var_buf[4];
static char var_string[16];
static char const *input_text;
static size_t input_index;
static int common_cntr;
static uint8_t ctx;
static int cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
return 0;
}
static int cmd2_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
sprintf(data, "%s=test", cmd->name);
*data_size = strlen(data);
return 0;
}
static int common_var_read_handler(const struct cat_variable *var)
{
common_cntr++;
return 0;
}
static void* var_int_data_getter(const struct cat_variable *var, void *context, size_t *data_size)
{
*data_size = sizeof(var_int);
assert(context == &ctx);
return &var_int;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_INT_DEC,
.read = common_var_read_handler,
.data_getter = var_int_data_getter,
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint,
.data_size = sizeof(var_uint),
.read = common_var_read_handler
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex8,
.data_size = sizeof(var_hex8),
.read = common_var_read_handler
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex16,
.data_size = sizeof(var_hex16),
.read = common_var_read_handler
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex32,
.data_size = sizeof(var_hex32),
.read = common_var_read_handler
},
{
.type = CAT_VAR_BUF_HEX,
.data = &var_buf,
.data_size = sizeof(var_buf),
.read = common_var_read_handler
},
{
.type = CAT_VAR_BUF_STRING,
.data = &var_string,
.data_size = sizeof(var_string),
.read = common_var_read_handler
}
};
static struct cat_command cmds[] = {
{
.name = "+SET",
.read = cmd_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
.context = &ctx,
},
{
.name = "+TEST",
.read = cmd2_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
.context = &ctx,
},
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_int = -1;
var_uint = 255;
var_hex8 = 0xAA;
var_hex16 = 0x0123;
var_hex32 = 0xFF001234;
var_buf[0] = 0x12;
var_buf[1] = 0x34;
var_buf[2] = 0x56;
var_buf[3] = 0x78;
common_cntr = 0;
sprintf(var_string, "\\\"test\n");
memset(ack_results, 0, sizeof(ack_results));
}
static const char test_case_1[] = "\nAT+SET?\r\n";
static const char test_case_2[] = "\nAT+TEST?\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\r\n+SET=-1,255,0xAA,0x0123,0xFF001234,12345678,\"\\\\\\\"test\\n\"\r\n\r\nOK\r\n") == 0);
assert(common_cntr == 7);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+TEST=test\n\nOK\n") == 0);
assert(common_cntr == 7);
return 0;
}

View File

@@ -0,0 +1,206 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char cmd_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x;
static struct cat_object at;
static cat_return_state ret;
static bool ret_error;
static cat_return_state cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(cmd_results, " read:");
strcat(cmd_results, cmd->name);
if (cat_is_hold(&at) == CAT_STATUS_HOLD) {
var_x++;
if (var_x > 4) {
ret = (ret_error == false) ? CAT_RETURN_STATE_HOLD_EXIT_OK : CAT_RETURN_STATE_HOLD_EXIT_ERROR;
} else {
if (var_x == 4) {
strcpy(data, "test");
*data_size = strlen(data);
}
ret = CAT_RETURN_STATE_DATA_NEXT;
}
} else {
if ((ret == CAT_RETURN_STATE_DATA_NEXT) || (ret == CAT_RETURN_STATE_NEXT)) {
var_x++;
if (var_x > 2)
ret = CAT_RETURN_STATE_DATA_OK;
} else if (ret == CAT_RETURN_STATE_HOLD) {
cat_trigger_unsolicited_read(&at, cmd);
}
}
return ret;
}
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x)
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.read = cmd_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_x = 1;
memset(ack_results, 0, sizeof(ack_results));
memset(cmd_results, 0, sizeof(cmd_results));
}
static const char test_case_1[] = "\nAT+CMD?\n";
int main(int argc, char **argv)
{
cat_status s;
cat_init(&at, &desc, &iface, NULL);
ret = CAT_RETURN_STATE_ERROR;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(strcmp(cmd_results, " read:+CMD") == 0);
ret = CAT_RETURN_STATE_DATA_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=1\n\nOK\n") == 0);
assert(strcmp(cmd_results, " read:+CMD") == 0);
ret = CAT_RETURN_STATE_DATA_NEXT;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=1\n\n+CMD=2\n\nOK\n") == 0);
assert(strcmp(cmd_results, " read:+CMD read:+CMD") == 0);
ret = CAT_RETURN_STATE_NEXT;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=2\n\nOK\n") == 0);
assert(strcmp(cmd_results, " read:+CMD read:+CMD") == 0);
ret = CAT_RETURN_STATE_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " read:+CMD") == 0);
ret_error = false;
ret = CAT_RETURN_STATE_HOLD;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=1\n\n+CMD=2\n\ntest\n\nOK\n") == 0);
assert(strcmp(cmd_results, " read:+CMD read:+CMD read:+CMD read:+CMD read:+CMD") == 0);
ret_error = true;
ret = CAT_RETURN_STATE_HOLD;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=1\n\n+CMD=2\n\ntest\n\nERROR\n") == 0);
assert(strcmp(cmd_results, " read:+CMD read:+CMD read:+CMD read:+CMD read:+CMD") == 0);
return 0;
}

View File

@@ -0,0 +1,236 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char cmd_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x;
static struct cat_object at;
static cat_return_state ret;
static bool ret_error;
static cat_return_state cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(cmd_results, " read:");
strcat(cmd_results, cmd->name);
var_x++;
if (var_x > 5) {
ret = (ret_error == false) ? CAT_RETURN_STATE_HOLD_EXIT_OK : CAT_RETURN_STATE_HOLD_EXIT_ERROR;
} else {
if (var_x == 5) {
strcpy(data, "test");
*data_size = strlen(data);
}
ret = CAT_RETURN_STATE_DATA_NEXT;
}
return ret;
}
static cat_return_state cmd_run(const struct cat_command *cmd)
{
strcat(cmd_results, " run:");
strcat(cmd_results, cmd->name);
if ((ret == CAT_RETURN_STATE_DATA_NEXT) || (ret == CAT_RETURN_STATE_NEXT)) {
var_x++;
if (var_x > 3)
ret = CAT_RETURN_STATE_DATA_OK;
} else if (ret == CAT_RETURN_STATE_HOLD) {
cat_trigger_unsolicited_read(&at, cmd);
}
return ret;
}
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x)
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.run = cmd_run,
.read = cmd_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_x = 2;
memset(ack_results, 0, sizeof(ack_results));
memset(cmd_results, 0, sizeof(cmd_results));
}
static const char test_case_1[] = "\nAT+CMD\n";
int main(int argc, char **argv)
{
cat_status s;
cat_init(&at, &desc, &iface, NULL);
ret = CAT_RETURN_STATE_ERROR;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(strcmp(cmd_results, " run:+CMD") == 0);
assert(var_x == 2);
ret = CAT_RETURN_STATE_DATA_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " run:+CMD") == 0);
assert(var_x == 2);
ret = CAT_RETURN_STATE_DATA_NEXT;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " run:+CMD run:+CMD") == 0);
assert(var_x == 4);
ret = CAT_RETURN_STATE_NEXT;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " run:+CMD run:+CMD") == 0);
assert(var_x == 4);
ret = CAT_RETURN_STATE_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " run:+CMD") == 0);
assert(var_x == 2);
ret_error = false;
ret = CAT_RETURN_STATE_HOLD;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=2\n\n+CMD=3\n\ntest\n\nOK\n") == 0);
assert(strcmp(cmd_results, " run:+CMD read:+CMD read:+CMD read:+CMD read:+CMD") == 0);
assert(var_x == 6);
ret_error = true;
ret = CAT_RETURN_STATE_HOLD;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=2\n\n+CMD=3\n\ntest\n\nERROR\n") == 0);
assert(strcmp(cmd_results, " run:+CMD read:+CMD read:+CMD read:+CMD read:+CMD") == 0);
assert(var_x == 6);
ret = CAT_RETURN_STATE_HOLD_EXIT_ERROR;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(strcmp(cmd_results, " run:+CMD") == 0);
assert(var_x == 2);
ret = CAT_RETURN_STATE_HOLD_EXIT_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(strcmp(cmd_results, " run:+CMD") == 0);
assert(var_x == 2);
return 0;
}

View File

@@ -0,0 +1,206 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char cmd_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x;
static struct cat_object at;
static cat_return_state ret;
static bool ret_error;
static cat_return_state cmd_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(cmd_results, " test:");
strcat(cmd_results, cmd->name);
if (cat_is_hold(&at) == CAT_STATUS_HOLD) {
var_x++;
if (var_x > 4) {
ret = (ret_error == false) ? CAT_RETURN_STATE_HOLD_EXIT_OK : CAT_RETURN_STATE_HOLD_EXIT_ERROR;
} else {
if (var_x == 4) {
strcpy(data, "test");
*data_size = strlen(data);
}
ret = CAT_RETURN_STATE_DATA_NEXT;
}
} else {
if ((ret == CAT_RETURN_STATE_DATA_NEXT) || (ret == CAT_RETURN_STATE_NEXT)) {
var_x++;
if (var_x > 2)
ret = CAT_RETURN_STATE_DATA_OK;
} else if (ret == CAT_RETURN_STATE_HOLD) {
cat_trigger_unsolicited_test(&at, cmd);
}
}
return ret;
}
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x)
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.test = cmd_test,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_x = 1;
memset(ack_results, 0, sizeof(ack_results));
memset(cmd_results, 0, sizeof(cmd_results));
}
static const char test_case_1[] = "\nAT+CMD=?\n";
int main(int argc, char **argv)
{
cat_status s;
cat_init(&at, &desc, &iface, NULL);
ret = CAT_RETURN_STATE_ERROR;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(strcmp(cmd_results, " test:+CMD") == 0);
ret = CAT_RETURN_STATE_DATA_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=<X:INT32[RW]>\n\nOK\n") == 0);
assert(strcmp(cmd_results, " test:+CMD") == 0);
ret = CAT_RETURN_STATE_DATA_NEXT;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=<X:INT32[RW]>\n\n+CMD=<X:INT32[RW]>\n\nOK\n") == 0);
assert(strcmp(cmd_results, " test:+CMD test:+CMD") == 0);
ret = CAT_RETURN_STATE_NEXT;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=<X:INT32[RW]>\n\nOK\n") == 0);
assert(strcmp(cmd_results, " test:+CMD test:+CMD") == 0);
ret = CAT_RETURN_STATE_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " test:+CMD") == 0);
ret_error = false;
ret = CAT_RETURN_STATE_HOLD;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=<X:INT32[RW]>\n\n+CMD=<X:INT32[RW]>\n\ntest\n\nOK\n") == 0);
assert(strcmp(cmd_results, " test:+CMD test:+CMD test:+CMD test:+CMD test:+CMD") == 0);
ret_error = true;
ret = CAT_RETURN_STATE_HOLD;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=<X:INT32[RW]>\n\n+CMD=<X:INT32[RW]>\n\ntest\n\nERROR\n") == 0);
assert(strcmp(cmd_results, " test:+CMD test:+CMD test:+CMD test:+CMD test:+CMD") == 0);
return 0;
}

View File

@@ -0,0 +1,236 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char cmd_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x;
static struct cat_object at;
static cat_return_state ret;
static bool ret_error;
static cat_return_state cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(cmd_results, " read:");
strcat(cmd_results, cmd->name);
var_x++;
if (var_x > 5) {
ret = (ret_error == false) ? CAT_RETURN_STATE_HOLD_EXIT_OK : CAT_RETURN_STATE_HOLD_EXIT_ERROR;
} else {
if (var_x == 5) {
strcpy(data, "test");
*data_size = strlen(data);
}
ret = CAT_RETURN_STATE_DATA_NEXT;
}
return ret;
}
static cat_return_state cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(cmd_results, " write:");
strcat(cmd_results, cmd->name);
if ((ret == CAT_RETURN_STATE_DATA_NEXT) || (ret == CAT_RETURN_STATE_NEXT)) {
var_x++;
if (var_x > 3)
ret = CAT_RETURN_STATE_DATA_OK;
} else if (ret == CAT_RETURN_STATE_HOLD) {
cat_trigger_unsolicited_read(&at, cmd);
}
return ret;
}
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x)
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.write = cmd_write,
.read = cmd_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_x = 1;
memset(ack_results, 0, sizeof(ack_results));
memset(cmd_results, 0, sizeof(cmd_results));
}
static const char test_case_1[] = "\nAT+CMD=2\n";
int main(int argc, char **argv)
{
cat_status s;
cat_init(&at, &desc, &iface, NULL);
ret = CAT_RETURN_STATE_ERROR;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(strcmp(cmd_results, " write:+CMD") == 0);
assert(var_x == 2);
ret = CAT_RETURN_STATE_DATA_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " write:+CMD") == 0);
assert(var_x == 2);
ret = CAT_RETURN_STATE_DATA_NEXT;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " write:+CMD write:+CMD") == 0);
assert(var_x == 4);
ret = CAT_RETURN_STATE_NEXT;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " write:+CMD write:+CMD") == 0);
assert(var_x == 4);
ret = CAT_RETURN_STATE_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(strcmp(cmd_results, " write:+CMD") == 0);
assert(var_x == 2);
ret_error = false;
ret = CAT_RETURN_STATE_HOLD;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=2\n\n+CMD=3\n\ntest\n\nOK\n") == 0);
assert(strcmp(cmd_results, " write:+CMD read:+CMD read:+CMD read:+CMD read:+CMD") == 0);
assert(var_x == 6);
ret_error = true;
ret = CAT_RETURN_STATE_HOLD;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+CMD=2\n\n+CMD=3\n\ntest\n\nERROR\n") == 0);
assert(strcmp(cmd_results, " write:+CMD read:+CMD read:+CMD read:+CMD read:+CMD") == 0);
assert(var_x == 6);
ret = CAT_RETURN_STATE_HOLD_EXIT_ERROR;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(strcmp(cmd_results, " write:+CMD") == 0);
assert(var_x == 2);
ret = CAT_RETURN_STATE_HOLD_EXIT_OK;
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(strcmp(cmd_results, " write:+CMD") == 0);
assert(var_x == 2);
return 0;
}

View File

@@ -0,0 +1,157 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char run_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int a_run(const struct cat_command *cmd)
{
strcat(run_results, " A:");
strcat(run_results, cmd->name);
return 0;
}
static int ap_run(const struct cat_command *cmd)
{
strcat(run_results, " AP:");
strcat(run_results, cmd->name);
return 0;
}
static int test_run(const struct cat_command *cmd)
{
strcat(run_results, " +TEST:");
strcat(run_results, cmd->name);
return 0;
}
static int force_run(const struct cat_command *cmd)
{
strcat(run_results, " FORCE:");
strcat(run_results, cmd->name);
return -1;
}
static struct cat_command cmds[] = {
{
.name = "A",
.run = a_run
},
{
.name = "AP",
.run = ap_run
},
{
.name = "+TEST",
.run = test_run
},
{
.name = "+EMPTY"
},
{
.name = "FORCE",
.run = force_run,
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(run_results, 0, sizeof(run_results));
memset(ack_results, 0, sizeof(ack_results));
}
static const char test_case_1[] = "\nAT\nAT+\nATA\r\nATAP\nATAPA\nAT+TEST\nAT+te\nAT+e\nAT+empTY\naTf\nAtFoRcE\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nERROR\n\r\nOK\r\n\nOK\n\nERROR\n\nOK\n\nOK\n\nERROR\n\nERROR\n\nERROR\n\nERROR\n") == 0);
assert(strcmp(run_results, " A:A AP:AP +TEST:+TEST +TEST:+TEST FORCE:FORCE FORCE:FORCE") == 0);
return 0;
}

View File

@@ -0,0 +1,224 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static int ap_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
return 0;
}
static int ap_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
return 0;
}
static struct cat_variable vars_ap1[] = {
{
.name = "var_ap1_1"
},
{
.name = "var_ap1_2"
},
{
.name = "var_ap1_3"
}
};
static struct cat_variable vars_apx2[] = {
{
.name = "var_apx2_1"
},
{
.name = "var_apx2_2"
},
{
.name = "var_apx2_3"
}
};
static struct cat_command cmds[] = {
{
.name = "AP1",
.write = ap_write,
.only_test = true,
.var = vars_ap1,
.var_num = sizeof(vars_ap1) / sizeof(vars_ap1[0])
},
{
.name = "AP2",
.read = ap_read,
.only_test = false
},
};
static struct cat_command cmds2[] = {
{
.name = "APX1",
.write = ap_write,
.only_test = true
},
{
.name = "APX2",
.read = ap_read,
.only_test = false,
.var = vars_apx2,
.var_num = sizeof(vars_apx2) / sizeof(vars_apx2[0])
},
};
static char buf[128];
static struct cat_command_group cmd_group1 = {
.name = "std",
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group cmd_group2 = {
.name = "ext",
.cmd = cmds2,
.cmd_num = sizeof(cmds2) / sizeof(cmds2[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group1,
&cmd_group2
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
return 1;
}
static int read_char(char *ch)
{
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
int main(int argc, char **argv)
{
struct cat_object at;
struct cat_command const *cmd;
struct cat_command_group const *cmd_group;
struct cat_variable const *var;
cat_init(&at, &desc, &iface, NULL);
cmd = cat_search_command_by_name(&at, "A");
assert(cmd == NULL);
cmd = cat_search_command_by_name(&at, "AP");
assert(cmd == NULL);
cmd = cat_search_command_by_name(&at, "AP1");
assert(cmd == &cmds[0]);
cmd = cat_search_command_by_name(&at, "AP2");
assert(cmd == &cmds[1]);
cmd = cat_search_command_by_name(&at, "AP3");
assert(cmd == NULL);
cmd = cat_search_command_by_name(&at, "APX1");
assert(cmd == &cmds2[0]);
cmd = cat_search_command_by_name(&at, "APX2");
assert(cmd == &cmds2[1]);
cmd = cat_search_command_by_name(&at, "APX3");
assert(cmd == NULL);
cmd_group = cat_search_command_group_by_name(&at, "std");
assert(cmd_group == cmd_desc[0]);
cmd_group = cat_search_command_group_by_name(&at, "ext");
assert(cmd_group == cmd_desc[1]);
cmd_group = cat_search_command_group_by_name(&at, "not");
assert(cmd_group == NULL);
var = cat_search_variable_by_name(&at, &cmds[0], "v");
assert(var == NULL);
var = cat_search_variable_by_name(&at, &cmds[0], "var_ap");
assert(var == NULL);
var = cat_search_variable_by_name(&at, &cmds[0], "var_apx2");
assert(var == NULL);
var = cat_search_variable_by_name(&at, &cmds[0], "var_ap1_1");
assert(var == &vars_ap1[0]);
var = cat_search_variable_by_name(&at, &cmds[0], "var_ap1_2");
assert(var == &vars_ap1[1]);
var = cat_search_variable_by_name(&at, &cmds[0], "var_ap1_3");
assert(var == &vars_ap1[2]);
var = cat_search_variable_by_name(&at, &cmds[0], "var_ap1_4");
assert(var == NULL);
var = cat_search_variable_by_name(&at, &cmds[1], "var_ap1_1");
assert(var == NULL);
var = cat_search_variable_by_name(&at, &cmds2[1], "var_apx2_1");
assert(var == &vars_apx2[0]);
var = cat_search_variable_by_name(&at, &cmds2[1], "var_apx2_2");
assert(var == &vars_apx2[1]);
var = cat_search_variable_by_name(&at, &cmds2[1], "var_apx2_3");
assert(var == &vars_apx2[2]);
var = cat_search_variable_by_name(&at, &cmds2[1], "var_apx2_4");
assert(var == NULL);
var = cat_search_variable_by_name(&at, &cmds2[0], "var_apx2_1");
assert(var == NULL);
return 0;
}

View File

@@ -0,0 +1,149 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char run_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int print_name(const struct cat_command *cmd)
{
strcat(run_results, cmd->name);
strcat(run_results, " ");
return 0;
}
static struct cat_command cmds[] = {
{
.name = "+TEST",
.run = print_name
},
{
.name = "+TEST_A",
.run = print_name
},
{
.name = "+TEST_B",
.run = print_name
},
{
.name = "+ONE",
.run = print_name
},
{
.name = "+TWO",
.run = print_name
},
};
static char buf[256];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(run_results, 0, sizeof(run_results));
memset(ack_results, 0, sizeof(ack_results));
}
static const char test_case_1[] = "\nAT\nAT+\nAT+T\nAT+TE\nAT+TES\nAT+TEST\nAT+TEST_\nAT+TEST_A\nAT+TEST_B\nAT+O\nAT+ON\nAT+ONE\nAT+TW\nAT+TWO\n";
static void print_raw_text(char *p)
{
while (*p != '\0') {
if (*p == '\n') {
printf("\\n");
} else {
putchar(*p);
}
p++;
}
}
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nERROR\n\nERROR\n\nERROR\n\nERROR\n\nOK\n\nERROR\n\nOK\n\nOK\n\nOK\n\nOK\n\nOK\n\nOK\n\nOK\n") == 0);
assert(strcmp(run_results, "+TEST +TEST_A +TEST_B +ONE +ONE +ONE +TWO +TWO ") == 0);
return 0;
}

View File

@@ -0,0 +1,183 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char test_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int a_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(test_results, " A:");
strcat(test_results, cmd->name);
snprintf(data, max_data_size, "%s=A-val", cmd->name);
*data_size = strlen(data);
return 0;
}
static int ap_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(test_results, " AP:");
strcat(test_results, cmd->name);
*data_size = 0;
return 0;
}
static int ap_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(test_results, " AP_W:");
strcat(test_results, cmd->name);
assert(args_num == 0);
assert(data[0] == 'a');
assert(data_size == 1);
return 0;
}
static int apw_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(test_results, " APW:");
strcat(test_results, cmd->name);
assert(args_num == 0);
assert(data[0] == '?');
assert(data_size == 1);
return 0;
}
static int test_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(test_results, " +TEST:");
strcat(test_results, cmd->name);
return -1;
}
static struct cat_command cmds[] = {
{
.name = "A",
.test = a_test
},
{
.name = "AP",
.test = ap_test,
.write = ap_write
},
{
.name = "APW",
.write = apw_write
},
{
.name = "+TEST",
.test = test_test
},
{
.name = "+EMPTY"
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(ack_results, 0, sizeof(ack_results));
memset(test_results, 0, sizeof(test_results));
}
static const char test_case_1[] = "\nAT\r\nAT\nATAP=?\nATAP=?a\nATAP=a\nATAPW=?\nAT+TEST=?\nATA=?\nAT+EMPTY=?\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\r\nOK\r\n\nOK\n\nAP=\n\nOK\n\nERROR\n\nOK\n\nOK\n\nERROR\n\nA=A-val\n\nOK\n\nERROR\n") == 0);
assert(strcmp(test_results, " AP:AP AP_W:AP APW:APW +TEST:+TEST A:A") == 0);
return 0;
}

View File

@@ -0,0 +1,459 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char ack_results[256];
static int8_t var_int8;
static int16_t var_int16;
static int32_t var_int32;
static uint8_t var_uint8;
static uint16_t var_uint16;
static uint32_t var_uint32;
static uint8_t var_hex8;
static uint16_t var_hex16;
static uint32_t var_hex32;
static uint8_t var_buf[4];
static char var_string[16];
static char const *input_text;
static size_t input_index;
static int cmd_override_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(data, "\ntest");
*data_size = strlen(data);
return 0;
}
static int cmd_error_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
return -1;
}
static int cmd_ok_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcpy(data, "test1");
*data_size = strlen(data);
return 0;
}
static int cmd_ok2_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(data, "test2");
*data_size = strlen(data);
return 0;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var_int8,
.data_size = sizeof(var_int8),
.name = "x"
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int16,
.data_size = sizeof(var_int16),
.name = "y"
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int32,
.data_size = sizeof(var_int32)
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint8,
.data_size = sizeof(var_uint8)
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint16,
.data_size = sizeof(var_uint16)
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint32,
.data_size = sizeof(var_uint32)
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex8,
.data_size = sizeof(var_hex8)
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex16,
.data_size = sizeof(var_hex16)
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex32,
.data_size = sizeof(var_hex32)
},
{
.type = CAT_VAR_BUF_HEX,
.data = &var_buf,
.data_size = sizeof(var_buf)
},
{
.type = CAT_VAR_BUF_STRING,
.data = &var_string,
.data_size = sizeof(var_string),
.name = "msg"
}
};
static struct cat_variable vars_ro[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var_int8,
.data_size = sizeof(var_int8),
.name = "x",
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int16,
.data_size = sizeof(var_int16),
.name = "y",
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int32,
.data_size = sizeof(var_int32),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint8,
.data_size = sizeof(var_uint8),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint16,
.data_size = sizeof(var_uint16),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint32,
.data_size = sizeof(var_uint32),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex8,
.data_size = sizeof(var_hex8),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex16,
.data_size = sizeof(var_hex16),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex32,
.data_size = sizeof(var_hex32),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_BUF_HEX,
.data = &var_buf,
.data_size = sizeof(var_buf),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_BUF_STRING,
.data = &var_string,
.data_size = sizeof(var_string),
.name = "msg",
.access = CAT_VAR_ACCESS_READ_ONLY
}
};
static struct cat_variable vars_wo[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var_int8,
.data_size = sizeof(var_int8),
.name = "x",
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int16,
.data_size = sizeof(var_int16),
.name = "y",
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int32,
.data_size = sizeof(var_int32),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint8,
.data_size = sizeof(var_uint8),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint16,
.data_size = sizeof(var_uint16),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint32,
.data_size = sizeof(var_uint32),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex8,
.data_size = sizeof(var_hex8),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex16,
.data_size = sizeof(var_hex16),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex32,
.data_size = sizeof(var_hex32),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_BUF_HEX,
.data = &var_buf,
.data_size = sizeof(var_buf),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_BUF_STRING,
.data = &var_string,
.data_size = sizeof(var_string),
.name = "msg",
.access = CAT_VAR_ACCESS_WRITE_ONLY
}
};
static struct cat_variable vars2[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var_int8,
.data_size = sizeof(var_int8),
.name = "var"
}
};
static struct cat_command cmds[] = {
{
.name = "+SET",
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+SETRO",
.var = vars_ro,
.var_num = sizeof(vars_ro) / sizeof(vars_ro[0])
},
{
.name = "+SETWO",
.var = vars_wo,
.var_num = sizeof(vars_wo) / sizeof(vars_wo[0])
},
{
.name = "+TEST",
.description = "test_desc",
.test = cmd_override_test,
.var = vars2,
.var_num = sizeof(vars2) / sizeof(vars2[0])
},
{
.name = "+TEST2",
.description = "test2_desc",
.var = vars2,
.var_num = sizeof(vars2) / sizeof(vars2[0])
},
{
.name = "+AP",
.test = cmd_error_test,
.var = vars2,
.var_num = sizeof(vars2) / sizeof(vars2[0])
},
{
.name = "+ZZ",
.test = cmd_ok_test,
},
{
.name = "+ZZ2",
.description = "zz2_desc",
.test = cmd_ok_test,
},
{
.name = "+ZZ3",
.description = "zz3_desc",
.test = cmd_ok2_test,
}
};
static char buf[256];
static char unsolicited_buf[256];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
.unsolicited_buf = unsolicited_buf,
.unsolicited_buf_size = sizeof(unsolicited_buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_int8 = -8;
var_int16 = -16;
var_int32 = -32;
var_uint8 = 8;
var_uint8 = 16;
var_uint8 = 32;
var_hex8 = 0x08;
var_hex16 = 0x16;
var_hex32 = 0x32;
var_hex16 = 0x0123;
var_hex32 = 0xFF001234;
var_buf[0] = 0x12;
var_buf[1] = 0x34;
var_buf[2] = 0x56;
var_buf[3] = 0x78;
sprintf(var_string, "TST");
memset(ack_results, 0, sizeof(ack_results));
}
static const char test_case_1[] = "\nAT+SET=?\n";
static const char test_case_1_ro[] = "\nAT+SETRO=?\n";
static const char test_case_1_wo[] = "\nAT+SETWO=?\n";
static const char test_case_2[] = "\nAT+TEST=?\nAT+TEST2=?\r\nAT+AP=?\n";
static const char test_case_3[] = "\nAT+ZZ=?\nAT+ZZ2=?\nAT+ZZ3=?\r\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+SET=<x:INT8[RW]>,<y:INT16[RW]>,<INT32[RW]>,<UINT8[RW]>,<UINT16[RW]>,<UINT32[RW]>,<HEX8[RW]>,<HEX16[RW]>,<HEX32[RW]>,<HEXBUF[RW]>,<msg:STRING[RW]>\n\nOK\n") == 0);
prepare_input(test_case_1_ro);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+SETRO=<x:INT8[RO]>,<y:INT16[RO]>,<INT32[RO]>,<UINT8[RO]>,<UINT16[RO]>,<UINT32[RO]>,<HEX8[RO]>,<HEX16[RO]>,<HEX32[RO]>,<HEXBUF[RO]>,<msg:STRING[RO]>\n\nOK\n") == 0);
prepare_input(test_case_1_wo);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+SETWO=<x:INT8[WO]>,<y:INT16[WO]>,<INT32[WO]>,<UINT8[WO]>,<UINT16[WO]>,<UINT32[WO]>,<HEX8[WO]>,<HEX16[WO]>,<HEX32[WO]>,<HEXBUF[WO]>,<msg:STRING[WO]>\n\nOK\n") == 0);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+TEST=<var:INT8[RW]>\ntest_desc\ntest\n\nOK\n\r\n+TEST2=<var:INT8[RW]>\r\ntest2_desc\r\n\r\nOK\r\n\nERROR\n") == 0);
prepare_input(test_case_3);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\ntest1\n\nOK\n\ntest1\n\nOK\n\r\n+ZZ3=\r\nzz3_desctest2\r\n\r\nOK\r\n") == 0);
return 0;
}

View File

@@ -0,0 +1,173 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char cmd_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int ap_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(cmd_results, " test:");
strcat(cmd_results, cmd->name);
strcpy(data, "ap_test");
*data_size = strlen(data);
return 0;
}
static int ap_run(const struct cat_command *cmd)
{
strcat(cmd_results, " run:");
strcat(cmd_results, cmd->name);
return 0;
}
static int ap_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
strcat(cmd_results, " read:");
strcat(cmd_results, cmd->name);
strcpy(data, "ap_read");
*data_size = strlen(data);
return 0;
}
static int ap_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(cmd_results, " write:");
strcat(cmd_results, cmd->name);
assert(strcmp(data, "1") == 0);
return 0;
}
static struct cat_command cmds[] = {
{
.name = "AP1",
.test = ap_test,
.write = ap_write,
.read = ap_read,
.run = ap_run,
.only_test = true
},
{
.name = "AP2",
.test = ap_test,
.write = ap_write,
.read = ap_read,
.run = ap_run,
.only_test = false
},
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(ack_results, 0, sizeof(ack_results));
memset(cmd_results, 0, sizeof(cmd_results));
}
static const char test_case_1[] = "\nATAP1=?\n\nATAP1?\n\nATAP1=1\n\nATAP1\n";
static const char test_case_2[] = "\nATAP2=?\n\nATAP2?\n\nATAP2=1\n\nATAP2\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nap_test\n\nOK\n\nERROR\n\nERROR\n\nERROR\n") == 0);
assert(strcmp(cmd_results, " test:AP1") == 0);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nap_test\n\nOK\n\nap_read\n\nOK\n\nOK\n\nOK\n") == 0);
assert(strcmp(cmd_results, " test:AP2 read:AP2 write:AP2 run:AP2") == 0);
return 0;
}

View File

@@ -0,0 +1,203 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char read_results[256];
static char var_read_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x, var_u1, var_u2;
static struct cat_object at;
static struct cat_command u_cmds[];
static cat_return_state cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
cat_status s;
strcat(read_results, " read:");
strcat(read_results, cmd->name);
if (strcmp(cmd->name, "+CMD") == 0) {
s = cat_trigger_unsolicited_read(&at, &u_cmds[1]);
assert(s == CAT_STATUS_OK);
}
return CAT_RETURN_STATE_DATA_OK;
}
static int var_read(const struct cat_variable *var)
{
strcat(var_read_results, " var_read:");
strcat(var_read_results, var->name);
return 0;
}
static struct cat_variable u_vars[] = {
{
.name = "U1",
.type = CAT_VAR_INT_DEC,
.data = &var_u1,
.data_size = sizeof(var_u1),
.read = var_read
},
{
.name = "U2",
.type = CAT_VAR_INT_DEC,
.data = &var_u2,
.data_size = sizeof(var_u2),
.read = var_read
}
};
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x),
.read = var_read
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.read = cmd_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static struct cat_command u_cmds[] = {
{
.name = "+U1CMD",
.read = cmd_read,
.var = &u_vars[0],
.var_num = 1,
},
{
.name = "+U2CMD",
.read = cmd_read,
.var = &u_vars[1],
.var_num = 1,
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_x = 1;
var_u1 = 2;
var_u2 = 3;
memset(ack_results, 0, sizeof(ack_results));
memset(read_results, 0, sizeof(read_results));
memset(var_read_results, 0, sizeof(var_read_results));
}
static const char test_case_1[] = "\nAT+CMD?\n";
int main(int argc, char **argv)
{
cat_status s;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
s = cat_is_unsolicited_buffer_full(&at);
assert(s == CAT_STATUS_OK);
s = cat_trigger_unsolicited_event(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_buffer_full(&at);
assert(s == CAT_STATUS_ERROR_BUFFER_FULL);
s = cat_trigger_unsolicited_read(&at, &u_cmds[1]);
assert(s == CAT_STATUS_ERROR_BUFFER_FULL);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+U1CMD=2\n\n+CMD=1\n\n+U2CMD=3\n\nOK\n") == 0);
assert(strcmp(read_results, " read:+U1CMD read:+CMD read:+U2CMD") == 0);
assert(strcmp(var_read_results, " var_read:U1 var_read:X var_read:U2") == 0);
return 0;
}

View File

@@ -0,0 +1,238 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char read_results[256];
static char var_read_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x, var_u1, var_u2;
static struct cat_object at;
static struct cat_command u_cmds[];
static cat_return_state cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
cat_status s;
strcat(read_results, " read:");
strcat(read_results, cmd->name);
if (strcmp(cmd->name, "+CMD") == 0) {
s = cat_trigger_unsolicited_read(&at, &u_cmds[1]);
assert(s == CAT_STATUS_OK);
}
return CAT_RETURN_STATE_DATA_OK;
}
static int var_read(const struct cat_variable *var)
{
strcat(var_read_results, " var_read:");
strcat(var_read_results, var->name);
return 0;
}
static struct cat_variable u_vars[] = {
{
.name = "U1",
.type = CAT_VAR_INT_DEC,
.data = &var_u1,
.data_size = sizeof(var_u1),
.read = var_read
},
{
.name = "U2",
.type = CAT_VAR_INT_DEC,
.data = &var_u2,
.data_size = sizeof(var_u2),
.read = var_read
}
};
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x),
.read = var_read
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.read = cmd_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static struct cat_command u_cmds[] = {
{
.name = "+U1CMD",
.read = cmd_read,
.var = &u_vars[0],
.var_num = 1,
},
{
.name = "+U2CMD",
.read = cmd_read,
.var = &u_vars[1],
.var_num = 1,
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_x = 1;
var_u1 = 2;
var_u2 = 3;
memset(ack_results, 0, sizeof(ack_results));
memset(read_results, 0, sizeof(read_results));
memset(var_read_results, 0, sizeof(var_read_results));
}
static const char test_case_1[] = "\nAT+CMD?\n";
int main(int argc, char **argv)
{
cat_status s;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
s = cat_is_unsolicited_buffer_full(&at);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_NONE);
assert(s == CAT_STATUS_OK);
s = cat_trigger_unsolicited_event(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_BUSY);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_TEST);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_NONE);
assert(s == CAT_STATUS_BUSY);
s = cat_is_unsolicited_buffer_full(&at);
assert(s == CAT_STATUS_OK);
s = cat_trigger_unsolicited_event(&at, &u_cmds[1], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_BUSY);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_TEST);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_NONE);
assert(s == CAT_STATUS_BUSY);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[1], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_BUSY);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[1], CAT_CMD_TYPE_TEST);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[1], CAT_CMD_TYPE_NONE);
assert(s == CAT_STATUS_BUSY);
s = cat_is_unsolicited_buffer_full(&at);
assert(s == CAT_STATUS_ERROR_BUFFER_FULL);
s = cat_trigger_unsolicited_read(&at, &u_cmds[1]);
assert(s == CAT_STATUS_ERROR_BUFFER_FULL);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_BUSY);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_TEST);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[1], CAT_CMD_TYPE_NONE);
assert(s == CAT_STATUS_BUSY);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+U1CMD=2\n\n+CMD=1\n\n+U2CMD=3\n\nOK\n\n+U2CMD=3\n") == 0);
assert(strcmp(read_results, " read:+U1CMD read:+CMD read:+U2CMD read:+U2CMD") == 0);
assert(strcmp(var_read_results, " var_read:U1 var_read:X var_read:U2 var_read:U2") == 0);
s = cat_is_unsolicited_buffer_full(&at);
assert(s == CAT_STATUS_OK);
return 0;
}

View File

@@ -0,0 +1,211 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char read_results[256];
static char var_read_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x, var_u1;
static struct cat_object at;
static struct cat_command u_cmds[];
static cat_return_state cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
cat_status s;
strcat(read_results, " read:");
strcat(read_results, cmd->name);
return CAT_RETURN_STATE_DATA_OK;
}
static int var_read(const struct cat_variable *var)
{
strcat(var_read_results, " var_read:");
strcat(var_read_results, var->name);
return 0;
}
static struct cat_variable u_vars[] = {
{
.name = "U1",
.type = CAT_VAR_INT_DEC,
.data = &var_u1,
.data_size = sizeof(var_u1),
.read = var_read
}
};
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x),
.read = var_read
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.read = cmd_read,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static struct cat_command u_cmds[] = {
{
.name = "+UCMD",
.read = cmd_read,
.var = u_vars,
.var_num = sizeof(u_vars) / sizeof(u_vars[0]),
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_x = 1;
var_u1 = 2;
memset(ack_results, 0, sizeof(ack_results));
memset(read_results, 0, sizeof(read_results));
memset(var_read_results, 0, sizeof(var_read_results));
}
static const char test_case_1[] = "\nAT+CMD?\n";
int main(int argc, char **argv)
{
cat_status s;
int events = 4;
struct cat_command const *cmd;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
cmd = cat_get_processed_command(&at, CAT_FSM_TYPE_ATCMD);
assert(cmd == NULL);
cmd = cat_get_processed_command(&at, CAT_FSM_TYPE_UNSOLICITED);
assert(cmd == NULL);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_NONE);
assert(s == CAT_STATUS_OK);
while (events > 0) {
s = cat_is_unsolicited_buffer_full(&at);
cmd = cat_get_processed_command(&at, CAT_FSM_TYPE_UNSOLICITED);
if ((s == CAT_STATUS_OK) && (cmd == NULL)) {
var_u1 = events;
s = cat_trigger_unsolicited_event(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_OK);
events--;
} else {
assert(cmd == &u_cmds[0]);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_READ);
assert(s == CAT_STATUS_BUSY);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_TEST);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_event_buffered(&at, &u_cmds[0], CAT_CMD_TYPE_NONE);
assert(s == CAT_STATUS_BUSY);
}
s = cat_service(&at);
assert(s == CAT_STATUS_BUSY);
}
while (cat_service(&at) != 0) {};
cmd = cat_get_processed_command(&at, CAT_FSM_TYPE_ATCMD);
assert(cmd == NULL);
cmd = cat_get_processed_command(&at, CAT_FSM_TYPE_UNSOLICITED);
assert(cmd == NULL);
assert(strcmp(ack_results, "\n+UCMD=4\n\n+CMD=1\n\n+UCMD=3\n\nOK\n\n+UCMD=2\n\n+UCMD=1\n") == 0);
assert(strcmp(read_results, " read:+UCMD read:+CMD read:+UCMD read:+UCMD read:+UCMD") == 0);
assert(strcmp(var_read_results, " var_read:U1 var_read:X var_read:U1 var_read:U1 var_read:U1") == 0);
return 0;
}

View File

@@ -0,0 +1,189 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char read_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int var_x, var_u1, var_u2;
static struct cat_object at;
static struct cat_command u_cmds[];
static cat_return_state cmd_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
cat_status s;
strcat(read_results, " test:");
strcat(read_results, cmd->name);
if (strcmp(cmd->name, "+CMD") == 0) {
s = cat_trigger_unsolicited_test(&at, &u_cmds[1]);
assert(s == CAT_STATUS_OK);
}
return CAT_RETURN_STATE_DATA_OK;
}
static struct cat_variable u_vars[] = {
{
.name = "U1",
.type = CAT_VAR_INT_DEC,
.data = &var_u1,
.data_size = sizeof(var_u1)
},
{
.name = "U2",
.type = CAT_VAR_INT_DEC,
.data = &var_u2,
.data_size = sizeof(var_u2)
}
};
static struct cat_variable vars[] = {
{
.name = "X",
.type = CAT_VAR_INT_DEC,
.data = &var_x,
.data_size = sizeof(var_x)
}
};
static struct cat_command cmds[] = {
{
.name = "+CMD",
.test = cmd_test,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
}
};
static struct cat_command u_cmds[] = {
{
.name = "+U1CMD",
.test = cmd_test,
.var = &u_vars[0],
.var_num = 1,
},
{
.name = "+U2CMD",
.test = cmd_test,
.var = &u_vars[1],
.var_num = 1,
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var_x = 1;
var_u1 = 2;
var_u2 = 3;
memset(ack_results, 0, sizeof(ack_results));
memset(read_results, 0, sizeof(read_results));
}
static const char test_case_1[] = "\nAT+CMD=?\n";
int main(int argc, char **argv)
{
cat_status s;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
s = cat_is_unsolicited_buffer_full(&at);
assert(s == CAT_STATUS_OK);
s = cat_trigger_unsolicited_event(&at, &u_cmds[0], CAT_CMD_TYPE_TEST);
assert(s == CAT_STATUS_OK);
s = cat_is_unsolicited_buffer_full(&at);
assert(s == CAT_STATUS_ERROR_BUFFER_FULL);
s = cat_trigger_unsolicited_test(&at, &u_cmds[1]);
assert(s == CAT_STATUS_ERROR_BUFFER_FULL);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+U1CMD=<U1:INT32[RW]>\n\n+CMD=<X:INT32[RW]>\n\n+U2CMD=<U2:INT32[RW]>\n\nOK\n") == 0);
assert(strcmp(read_results, " test:+U1CMD test:+CMD test:+U2CMD") == 0);
return 0;
}

View File

@@ -0,0 +1,545 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char ack_results[256];
static int8_t var1;
static int8_t var2;
static int8_t var3;
static char const *input_text;
static size_t input_index;
static int var2_write_cntr;
static int var3_read_cntr;
static int8_t var_int8;
static int16_t var_int16;
static int32_t var_int32;
static uint8_t var_uint8;
static uint16_t var_uint16;
static uint32_t var_uint32;
static uint8_t var_hex8;
static uint16_t var_hex16;
static uint32_t var_hex32;
static uint8_t var_buf[4];
static char var_string[16];
static int cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
return 0;
}
static int cmd_read(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
return 0;
}
static int cmd_test(const struct cat_command *cmd, uint8_t *data, size_t *data_size, const size_t max_data_size)
{
return 0;
}
static int cmd_run(const struct cat_command *cmd)
{
return 0;
}
static int var1_write(const struct cat_variable *var, size_t write_size)
{
return 0;
}
static int var1_read(const struct cat_variable *var)
{
return 0;
}
static int var2_write(const struct cat_variable *var, size_t write_size)
{
var2_write_cntr++;
return 0;
}
static int var2_read(const struct cat_variable *var)
{
return 0;
}
static int var3_write(const struct cat_variable *var, size_t write_size)
{
return 0;
}
static int var3_read(const struct cat_variable *var)
{
var3_read_cntr++;
return 0;
}
static int print_cmd_list(const struct cat_command *cmd)
{
return CAT_RETURN_STATE_PRINT_CMD_LIST_OK;
}
static struct cat_variable vars_ro[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write,
.read = var2_read,
.access = CAT_VAR_ACCESS_READ_ONLY
}
};
static struct cat_variable vars_wo[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var3,
.data_size = sizeof(var3),
.write = var3_write,
.read = var3_read,
.access = CAT_VAR_ACCESS_WRITE_ONLY
}
};
static struct cat_variable vars[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write,
.read = var1_read,
.access = CAT_VAR_ACCESS_READ_WRITE
},
{
.type = CAT_VAR_INT_DEC,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write,
.read = var2_read,
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var3,
.data_size = sizeof(var3),
.write = var3_write,
.read = var3_read,
.access = CAT_VAR_ACCESS_WRITE_ONLY
}
};
static struct cat_variable vars_misc_ro[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.access = CAT_VAR_ACCESS_READ_WRITE
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int8,
.data_size = sizeof(var_int8),
.name = "x",
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int16,
.data_size = sizeof(var_int16),
.name = "y",
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int32,
.data_size = sizeof(var_int32),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint8,
.data_size = sizeof(var_uint8),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint16,
.data_size = sizeof(var_uint16),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint32,
.data_size = sizeof(var_uint32),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex8,
.data_size = sizeof(var_hex8),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex16,
.data_size = sizeof(var_hex16),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex32,
.data_size = sizeof(var_hex32),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_BUF_HEX,
.data = &var_buf,
.data_size = sizeof(var_buf),
.access = CAT_VAR_ACCESS_READ_ONLY
},
{
.type = CAT_VAR_BUF_STRING,
.data = &var_string,
.data_size = sizeof(var_string),
.name = "msg",
.access = CAT_VAR_ACCESS_READ_ONLY
}
};
static struct cat_variable vars_misc_wo[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.access = CAT_VAR_ACCESS_READ_WRITE
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int8,
.data_size = sizeof(var_int8),
.name = "x",
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int16,
.data_size = sizeof(var_int16),
.name = "y",
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_INT_DEC,
.data = &var_int32,
.data_size = sizeof(var_int32),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint8,
.data_size = sizeof(var_uint8),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint16,
.data_size = sizeof(var_uint16),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var_uint32,
.data_size = sizeof(var_uint32),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex8,
.data_size = sizeof(var_hex8),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex16,
.data_size = sizeof(var_hex16),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var_hex32,
.data_size = sizeof(var_hex32),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_BUF_HEX,
.data = &var_buf,
.data_size = sizeof(var_buf),
.access = CAT_VAR_ACCESS_WRITE_ONLY
},
{
.type = CAT_VAR_BUF_STRING,
.data = &var_string,
.data_size = sizeof(var_string),
.name = "msg",
.access = CAT_VAR_ACCESS_WRITE_ONLY
}
};
static struct cat_command cmds[] = {
{
.name = "+VRW",
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+VRO",
.var = vars_ro,
.var_num = sizeof(vars_ro) / sizeof(vars_ro[0])
},
{
.name = "+VWO",
.var = vars_wo,
.var_num = sizeof(vars_wo) / sizeof(vars_wo[0])
},
{
.name = "+MRO",
.var = vars_misc_ro,
.var_num = sizeof(vars_misc_ro) / sizeof(vars_misc_ro[0])
},
{
.name = "+MWO",
.var = vars_misc_wo,
.var_num = sizeof(vars_misc_wo) / sizeof(vars_misc_wo[0])
},
{
.name = "#HELP",
.run = print_cmd_list,
}
};
static char buf[256];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(ack_results, 0, sizeof(ack_results));
}
static void print_raw_text(char *p)
{
while (*p != '\0') {
if (*p == '\n') {
printf("\\n");
} else {
putchar(*p);
}
p++;
}
}
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input("\nAT#HELP\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nAT+VRW?\nAT+VRW=\nAT+VRW=?\n\nAT+VRO?\nAT+VRO=?\n\nAT+VWO=\nAT+VWO=?\n\nAT+MRO?\nAT+MRO=\nAT+MRO=?\n\nAT+MWO?\nAT+MWO=\nAT+MWO=?\n\nAT#HELP\n\nOK\n") == 0);
prepare_input("\nAT+VRW=?\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+VRW=<INT8[RW]>,<INT8[RO]>,<INT8[WO]>\n\nOK\n") == 0);
prepare_input("\nAT+VRO=?\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+VRO=<INT8[RO]>\n\nOK\n") == 0);
prepare_input("\nAT+VWO=?\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+VWO=<INT8[WO]>\n\nOK\n") == 0);
var2 = 1;
prepare_input("\nAT+VRO=1\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(var2 == 1);
var3 = 3;
prepare_input("\nAT+VWO?\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n") == 0);
assert(var3 == 3);
var1 = -1;
var2 = -2;
var3 = -3;
var2_write_cntr = 0;
var3_read_cntr = 0;
prepare_input("\nAT+VRW?\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+VRW=-1,-2,0\n\nOK\n") == 0);
assert(var2_write_cntr == 0);
assert(var3_read_cntr == 1);
prepare_input("\nAT+VRW=1,2,3\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(var2_write_cntr == 1);
assert(var3_read_cntr == 1);
assert(var1 == 1);
assert(var2 == -2);
assert(var3 == 3);
var1 = 100;
var_int8 = 1;
var_int16 = 2;
var_int32 = 3;
var_uint8 = 4;
var_uint16 = 5;
var_uint32 = 6;
var_hex8 = 7;
var_hex16 = 8;
var_hex32 = 9;
var_buf[0] = 0x10;
var_buf[1] = 0x11;
var_buf[2] = 0x12;
var_buf[3] = 0x13;
strcpy(var_string, "test_string");
prepare_input("\nAT+MWO?\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+MWO=100,0,0,0,0,0,0,0x00,0x0000,0x00000000,00000000,\"\"\n\nOK\n") == 0);
prepare_input("\nAT+MWO=1,2,3,4,5,6,7,0x08,0x0009,0x0000000A,01020304,\"abc\"\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(var1 == 1);
assert(var_int8 == 2);
assert(var_int16 == 3);
assert(var_int32 == 4);
assert(var_uint8 == 5);
assert(var_uint16 == 6);
assert(var_uint32 == 7);
assert(var_hex8 == 8);
assert(var_hex16 == 9);
assert(var_hex32 == 10);
assert(var_buf[0] == 0x01);
assert(var_buf[1] == 0x02);
assert(var_buf[2] == 0x03);
assert(var_buf[3] == 0x04);
assert(strcmp(var_string, "abc") == 0);
prepare_input("\nAT+MRO?\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\n+MRO=1,2,3,4,5,6,7,0x08,0x0009,0x0000000A,01020304,\"abc\"\n\nOK\n") == 0);
prepare_input("\nAT+MRO=2,0,0,0,0,0,0,0x00,0x0000,0x00000000,00000000,\"cba\"\n");
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n") == 0);
assert(var1 == 2);
assert(var_int8 == 2);
assert(var_int16 == 3);
assert(var_int32 == 4);
assert(var_uint8 == 5);
assert(var_uint16 == 6);
assert(var_uint32 == 7);
assert(var_hex8 == 8);
assert(var_hex16 == 9);
assert(var_hex32 == 10);
assert(var_buf[0] == 0x01);
assert(var_buf[1] == 0x02);
assert(var_buf[2] == 0x03);
assert(var_buf[3] == 0x04);
assert(strcmp(var_string, "abc") == 0);
return 0;
}

View File

@@ -0,0 +1,166 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char run_results[256];
static char write_results[256];
static char ack_results[256];
static char const *input_text;
static size_t input_index;
static int a_run(const struct cat_command *cmd)
{
strcat(run_results, " A_");
strcat(run_results, cmd->name);
return 0;
}
static int a_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(write_results, " A:");
strncat(write_results, data, data_size);
assert(args_num == 0);
return 0;
}
static int ap_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(write_results, " AP:");
strncat(write_results, data, data_size);
assert(args_num == 0);
return 0;
}
static int test_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(write_results, " +TEST:");
strncat(write_results, data, data_size);
assert(args_num == 0);
return -1;
}
static struct cat_command cmds[] = {
{
.name = "A",
.write = a_write,
.run = a_run
},
{
.name = "AP",
.write = ap_write
},
{
.name = "+TEST",
.write = test_write
},
{
.name = "+EMPTY"
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(run_results, 0, sizeof(run_results));
memset(ack_results, 0, sizeof(ack_results));
memset(write_results, 0, sizeof(write_results));
}
static const char test_case_1[] = "\nAT\nAT+\nAT+?\nATA=123\r\nATA=\nATAP?\nATAP=11\r22\r\nAT+TEST=456\nAT+te=789\nAT+e=1\nAT+empTY=2\r\nATA\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nERROR\n\nERROR\n\r\nOK\r\n\nOK\n\nERROR\n\r\nOK\r\n\nERROR\n\nERROR\n\nERROR\n\r\nERROR\r\n\nOK\n") == 0);
assert(strcmp(run_results, " A_A") == 0);
assert(strcmp(write_results, " A:123 A: AP:1122 +TEST:456 +TEST:789") == 0);
return 0;
}

View File

@@ -0,0 +1,174 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char write_results[256];
static char ack_results[256];
static uint8_t var[4];
static size_t var_write_size[4];
static int var_write_size_index;
static char const *input_text;
static size_t input_index;
static int cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(write_results, " CMD:");
strncat(write_results, data, data_size);
return 0;
}
static int var_write(const struct cat_variable *var, size_t write_size)
{
var_write_size[var_write_size_index++] = write_size;
return 0;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_BUF_HEX,
.data = var,
.data_size = sizeof(var),
.write = var_write
}
};
static struct cat_command cmds[] = {
{
.name = "+SET",
.write = cmd_write,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(var, 0, sizeof(var));
memset(var_write_size, 0, sizeof(var_write_size));
var_write_size_index = 0;
memset(ack_results, 0, sizeof(ack_results));
memset(write_results, 0, sizeof(write_results));
}
static const char test_case_1[] = "\nAT+SET=0\nAT+SET=aa\nAT+SET=001\nAT+SET=12345678\nAT+SET=ffAA\n";
static const char test_case_2[] = "\nAT+SET=0x11\nAT+SET=11\nAT+SET=-1\nAT+SET=87654321\nAT+SET=0001\nAT+SET=1122334455\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nERROR\n\nOK\n\nOK\n") == 0);
assert(strcmp(write_results, " CMD:aa CMD:12345678 CMD:ffAA") == 0);
assert(var[0] == 0xFF);
assert(var[1] == 0xAA);
assert(var[2] == 0x56);
assert(var[3] == 0x78);
assert(var_write_size[0] == 1);
assert(var_write_size[1] == 4);
assert(var_write_size[2] == 2);
assert(var_write_size[3] == 0);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nERROR\n\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:11 CMD:87654321 CMD:0001") == 0);
assert(var[0] == 0x11);
assert(var[1] == 0x22);
assert(var[2] == 0x33);
assert(var[3] == 0x44);
assert(var_write_size[0] == 1);
assert(var_write_size[1] == 4);
assert(var_write_size[2] == 2);
assert(var_write_size[3] == 0);
return 0;
}

View File

@@ -0,0 +1,212 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char write_results[256];
static char ack_results[256];
static uint8_t var1, var1b;
static uint16_t var2, var2b;
static uint32_t var3, var3b;
static char const *input_text;
static size_t input_index;
static int cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(write_results, " CMD:");
strncat(write_results, data, data_size);
return 0;
}
static int var1_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 1);
var1b = *(uint8_t*)(var->data);
return 0;
}
static int var2_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 2);
var2b = *(uint16_t*)(var->data);
return 0;
}
static int var3_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 4);
var3b = *(uint32_t*)(var->data);
return 0;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_NUM_HEX,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write
},
{
.type = CAT_VAR_NUM_HEX,
.data = &var3,
.data_size = sizeof(var3),
.write = var3_write
}
};
static struct cat_command cmds[] = {
{
.name = "+SET",
.write = cmd_write,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var1 = 1;
var2 = 2;
var3 = 3;
var1b = 10;
var2b = 20;
var3b = 30;
memset(ack_results, 0, sizeof(ack_results));
memset(write_results, 0, sizeof(write_results));
}
static const char test_case_1[] = "\nAT+SET=0\nAT+SET=0x0\nAT+SET=0x01\nAT+SET=0x0ff\nAT+SET=0x100\n";
static const char test_case_2[] = "\nAT+SET=0x,0x00\nAT+SET=0x1,0x00\nAT+SET=0x2,0xFFf\nAT+SET=0x3,0xFFFF\nAT+SET=0x4,0xFFFFF\n";
static const char test_case_3[] = "\nAT+SET=0x0,0x0,0\nAT+SET=0x0,0x0,0x0000000000000\nAT+SET=0x0,0x0,0x1\nAT+SET=0x0,0x0,0xffffFFFF\nAT+SET=0x10,0x20,0x100000000\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:0x0 CMD:0x01 CMD:0x0ff") == 0);
assert(var1 == 255);
assert(var1b == var1);
assert(var2 == 2);
assert(var2b == 20);
assert(var3 == 3);
assert(var3b == 30);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:0x1,0x00 CMD:0x2,0xFFf CMD:0x3,0xFFFF") == 0);
assert(var1 == 4);
assert(var1b == var1);
assert(var2 == 0xFFFF);
assert(var2b == var2);
assert(var3 == 3);
assert(var3b == 30);
prepare_input(test_case_3);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:0x0,0x0,0x0000000000000 CMD:0x0,0x0,0x1 CMD:0x0,0x0,0xffffFFFF") == 0);
assert(var1 == 0x10);
assert(var1b == var1);
assert(var2 == 0x20);
assert(var2b == var2);
assert(var3 == 0xFFFFFFFF);
assert(var3b == var3);
return 0;
}

View File

@@ -0,0 +1,212 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char write_results[256];
static char ack_results[256];
static int8_t var1, var1b;
static int16_t var2, var2b;
static int32_t var3, var3b;
static char const *input_text;
static size_t input_index;
static int cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(write_results, " CMD:");
strncat(write_results, data, data_size);
return 0;
}
static int var1_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 1);
var1b = *(int8_t*)(var->data);
return 0;
}
static int var2_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 2);
var2b = *(int16_t*)(var->data);
return 0;
}
static int var3_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 4);
var3b = *(int32_t*)(var->data);
return 0;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write
},
{
.type = CAT_VAR_INT_DEC,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write
},
{
.type = CAT_VAR_INT_DEC,
.data = &var3,
.data_size = sizeof(var3),
.write = var3_write
}
};
static struct cat_command cmds[] = {
{
.name = "+SET",
.write = cmd_write,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf),
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var1 = 1;
var2 = 2;
var3 = 3;
var1b = -1;
var2b = -2;
var3b = -3;
memset(ack_results, 0, sizeof(ack_results));
memset(write_results, 0, sizeof(write_results));
}
static const char test_case_1[] = "\nAT+SET=-128\nAT+SET=-129\nAT+SET=127\nAT+SET=128\n";
static const char test_case_2[] = "\nAT+SET=-128,-32768\nAT+SET=-128,-40000\nAT+SET=-128,32767\nAT+SET=-100,40000\n";
static const char test_case_3[] = "\nAT+SET=0,0,-2147483648\nAT+SET=0,0,-2147483649\nAT+SET=1,1,2147483647\nAT+SET=2,2,2147483648\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nERROR\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:-128 CMD:127") == 0);
assert(var1 == 127);
assert(var1b == var1);
assert(var2 == 2);
assert(var2b == -2);
assert(var3 == 3);
assert(var3b == -3);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nERROR\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:-128,-32768 CMD:-128,32767") == 0);
assert(var1 == -100);
assert(var1b == var1);
assert(var2 == 32767);
assert(var2b == var2);
assert(var3 == 3);
assert(var3b == -3);
prepare_input(test_case_3);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nERROR\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:0,0,-2147483648 CMD:1,1,2147483647") == 0);
assert(var1 == 2);
assert(var1b == var1);
assert(var2 == 2);
assert(var2b == var2);
assert(var3 == 2147483647);
assert(var3b == var3);
return 0;
}

View File

@@ -0,0 +1,234 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char write_results[256];
static char ack_results[256];
static int8_t var1, var2, var3;
static int8_t var1b, var2b, var3b;
static char const *input_text;
static size_t input_index;
static int cmd_write1(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
char tmp[32];
sprintf(tmp, " CMD1_%ld:", args_num);
strcat(write_results, tmp);
strncat(write_results, data, data_size);
return 0;
}
static int cmd_write3(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
char tmp[32];
sprintf(tmp, " CMD3_%ld:", args_num);
strcat(write_results, tmp);
strncat(write_results, data, data_size);
return 0;
}
static int var1_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 1);
var1b = *(int8_t*)(var->data);
return 0;
}
static int var2_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 1);
var2b = *(int8_t*)(var->data);
return 0;
}
static int var3_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 1);
var3b = *(int8_t*)(var->data);
return 0;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_INT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write
},
{
.type = CAT_VAR_INT_DEC,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write
},
{
.type = CAT_VAR_INT_DEC,
.data = &var3,
.data_size = sizeof(var3),
.write = var3_write
}
};
static struct cat_command cmds[] = {
{
.name = "+SET1",
.write = cmd_write1,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+SET3",
.write = cmd_write3,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
},
{
.name = "+SETALL",
.write = cmd_write3,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0]),
.need_all_vars = true
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var1 = 1;
var2 = 2;
var3 = 3;
memset(ack_results, 0, sizeof(ack_results));
memset(write_results, 0, sizeof(write_results));
}
static const char test_case_1[] = "\nAT+SET=-10,-20,-30\r\nAT+SET1=-10,-20,-30\r\nAT+SET1=-1\r\n";
static const char test_case_2[] = "\nAT+SET3=-1,-2,-3,0\nAT+SET3=-1,-2,-3\nAT+SET3=-100\n";
static const char test_case_3[] = "\nAT+SETALL=-11,-22,-33\nAT+SETALL=-1,-2,-3\nAT+SETALL=100\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\r\nERROR\r\n\r\nOK\r\n\r\nOK\r\n") == 0);
assert(strcmp(write_results, " CMD1_3:-10,-20,-30 CMD1_1:-1") == 0);
assert(var1 == -1);
assert(var2 == -20);
assert(var3 == -30);
assert(var1b == -1);
assert(var2b == -20);
assert(var3b == -30);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nOK\n") == 0);
assert(strcmp(write_results, " CMD3_3:-1,-2,-3 CMD3_1:-100") == 0);
assert(var1 == -100);
assert(var2 == -2);
assert(var3 == -3);
assert(var1b == -100);
assert(var2b == -2);
assert(var3b == -3);
prepare_input(test_case_3);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD3_3:-11,-22,-33 CMD3_3:-1,-2,-3") == 0);
assert(var1 == 100);
assert(var2 == -2);
assert(var3 == -3);
assert(var1b == 100);
assert(var2b == -2);
assert(var3b == -3);
return 0;
}

View File

@@ -0,0 +1,168 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char write_results[256];
static char ack_results[256];
static uint8_t var[8];
static size_t var_write_size[4];
static int var_write_size_index;
static char const *input_text;
static size_t input_index;
static int cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(write_results, " CMD:");
strncat(write_results, data, data_size);
return 0;
}
static int var_write(const struct cat_variable *var, size_t write_size)
{
var_write_size[var_write_size_index++] = write_size;
return 0;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_BUF_STRING,
.data = var,
.data_size = sizeof(var),
.write = var_write
}
};
static struct cat_command cmds[] = {
{
.name = "+SET",
.write = cmd_write,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
memset(var, 0, sizeof(var));
memset(var_write_size, 0, sizeof(var_write_size));
var_write_size_index = 0;
memset(ack_results, 0, sizeof(ack_results));
memset(write_results, 0, sizeof(write_results));
}
static const char test_case_1[] = "\nAT+SET=0\nAT+SET=\"\\\"abcd\\\"\"\nAT+SET=\"\"a\nAT+SET=\"1122334\"\nAT+SET=\"t\"\r\n";
static const char test_case_2[] = "\nAT+SET=\"12345678\"\nAT+SET=\"\"\nAT+SET=\"\\\\\\\\\"\nAT+SET=\"r1\\nr2\\n\"\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nERROR\n\nOK\n\r\nOK\r\n") == 0);
assert(strcmp(write_results, " CMD:\"\\\"abcd\\\"\" CMD:\"1122334\" CMD:\"t\"") == 0);
assert(strcmp(var, "t") == 0);
assert(var_write_size[0] == 6);
assert(var_write_size[1] == 7);
assert(var_write_size[2] == 1);
assert(var_write_size[3] == 0);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nOK\n\nOK\n") == 0);
assert(strcmp(write_results, " CMD:\"\" CMD:\"\\\\\\\\\" CMD:\"r1\\nr2\\n\"") == 0);
assert(strcmp(var, "r1\nr2\n") == 0);
assert(var_write_size[0] == 0);
assert(var_write_size[1] == 2);
assert(var_write_size[2] == 6);
assert(var_write_size[3] == 0);
return 0;
}

View File

@@ -0,0 +1,212 @@
/*
MIT License
Copyright (c) 2019 Marcin Borowicz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
#include <assert.h>
#include "../src/cat.h"
static char write_results[256];
static char ack_results[256];
static uint8_t var1, var1b;
static uint16_t var2, var2b;
static uint32_t var3, var3b;
static char const *input_text;
static size_t input_index;
static int cmd_write(const struct cat_command *cmd, const uint8_t *data, const size_t data_size, const size_t args_num)
{
strcat(write_results, " CMD:");
strncat(write_results, data, data_size);
return 0;
}
static int var1_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 1);
var1b = *(uint8_t*)(var->data);
return 0;
}
static int var2_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 2);
var2b = *(uint16_t*)(var->data);
return 0;
}
static int var3_write(const struct cat_variable *var, size_t write_size)
{
assert(write_size == 4);
var3b = *(uint32_t*)(var->data);
return 0;
}
static struct cat_variable vars[] = {
{
.type = CAT_VAR_UINT_DEC,
.data = &var1,
.data_size = sizeof(var1),
.write = var1_write
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var2,
.data_size = sizeof(var2),
.write = var2_write
},
{
.type = CAT_VAR_UINT_DEC,
.data = &var3,
.data_size = sizeof(var3),
.write = var3_write
}
};
static struct cat_command cmds[] = {
{
.name = "+SET",
.write = cmd_write,
.var = vars,
.var_num = sizeof(vars) / sizeof(vars[0])
}
};
static char buf[128];
static struct cat_command_group cmd_group = {
.cmd = cmds,
.cmd_num = sizeof(cmds) / sizeof(cmds[0]),
};
static struct cat_command_group *cmd_desc[] = {
&cmd_group
};
static struct cat_descriptor desc = {
.cmd_group = cmd_desc,
.cmd_group_num = sizeof(cmd_desc) / sizeof(cmd_desc[0]),
.buf = buf,
.buf_size = sizeof(buf)
};
static int write_char(char ch)
{
char str[2];
str[0] = ch;
str[1] = 0;
strcat(ack_results, str);
return 1;
}
static int read_char(char *ch)
{
if (input_index >= strlen(input_text))
return 0;
*ch = input_text[input_index];
input_index++;
return 1;
}
static struct cat_io_interface iface = {
.read = read_char,
.write = write_char
};
static void prepare_input(const char *text)
{
input_text = text;
input_index = 0;
var1 = 1;
var2 = 2;
var3 = 3;
var1b = 10;
var2b = 20;
var3b = 30;
memset(ack_results, 0, sizeof(ack_results));
memset(write_results, 0, sizeof(write_results));
}
static const char test_case_1[] = "\nAT+SET=-128\nAT+SET=0\nAT+SET=255\nAT+SET=256\n";
static const char test_case_2[] = "\nAT+SET=0,-1\nAT+SET=0,0\nAT+SET=0,65535\nAT+SET=1,65536\n";
static const char test_case_3[] = "\nAT+SET=0,0,-1\nAT+SET=0,0,0\nAT+SET=1,1,4294967295\nAT+SET=2,2,4294967296\n";
int main(int argc, char **argv)
{
struct cat_object at;
cat_init(&at, &desc, &iface, NULL);
prepare_input(test_case_1);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:0 CMD:255") == 0);
assert(var1 == 255);
assert(var1b == var1);
assert(var2 == 2);
assert(var2b == 20);
assert(var3 == 3);
assert(var3b == 30);
prepare_input(test_case_2);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:0,0 CMD:0,65535") == 0);
assert(var1 == 1);
assert(var1b == var1);
assert(var2 == 65535);
assert(var2b == var2);
assert(var3 == 3);
assert(var3b == 30);
prepare_input(test_case_3);
while (cat_service(&at) != 0) {};
assert(strcmp(ack_results, "\nERROR\n\nOK\n\nOK\n\nERROR\n") == 0);
assert(strcmp(write_results, " CMD:0,0,0 CMD:1,1,4294967295") == 0);
assert(var1 == 2);
assert(var1b == var1);
assert(var2 == 2);
assert(var2b == var2);
assert(var3 == 4294967295);
assert(var3b == var3);
return 0;
}

6
components/api/src/api.c Executable file
View File

@@ -0,0 +1,6 @@
#include "api.h"
void api_init(void)
{
//modbus_init();
}

534
components/api/src/json.c Executable file
View File

@@ -0,0 +1,534 @@
#include <string.h>
#include "sdkconfig.h"
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "esp_ota_ops.h"
#include "esp_timer.h"
#include "esp_chip_info.h"
#include "esp_mac.h"
#include "json.h"
#include "mqtt.h"
#include "wifi.h"
#include "timeout_utils.h"
#include "evse_error.h"
#include "evse_api.h"
#include "ocpp.h"
#include "board_config.h"
#include "energy_meter.h"
#include "socket_lock.h"
#include "proximity.h"
//#include "modbus.h"
//#include "modbus_tcp.h"
#include "rest.h"
#include "temp_sensor.h"
// #include "script.h"
#include "date_time.h"
#define RETURN_ON_ERROR(x) \
do \
{ \
esp_err_t err_rc_ = (x); \
if (unlikely(err_rc_ != ESP_OK)) \
{ \
return err_rc_; \
} \
} while (0)
cJSON *json_get_evse_config(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, "maxChargingCurrent", evse_get_max_charging_current());
cJSON_AddNumberToObject(root, "chargingCurrent", evse_get_charging_current() / 10.0);
cJSON_AddNumberToObject(root, "defaultChargingCurrent", evse_get_default_charging_current() / 10.0);
cJSON_AddBoolToObject(root, "requireAuth", evse_is_require_auth());
cJSON_AddBoolToObject(root, "socketOutlet", evse_get_socket_outlet());
cJSON_AddBoolToObject(root, "rcm", evse_is_rcm());
cJSON_AddNumberToObject(root, "temperatureThreshold", evse_get_temp_threshold());
cJSON_AddNumberToObject(root, "consumptionLimit", evse_get_consumption_limit());
cJSON_AddNumberToObject(root, "defaultConsumptionLimit", evse_get_default_consumption_limit());
cJSON_AddNumberToObject(root, "chargingTimeLimit", evse_get_charging_time_limit());
cJSON_AddNumberToObject(root, "defaultChargingTimeLimit", evse_get_default_charging_time_limit());
cJSON_AddNumberToObject(root, "underPowerLimit", evse_get_under_power_limit());
cJSON_AddNumberToObject(root, "defaultUnderPowerLimit", evse_get_default_under_power_limit());
cJSON_AddNumberToObject(root, "socketLockOperatingTime", socket_lock_get_operating_time());
cJSON_AddNumberToObject(root, "socketLockBreakTime", socket_lock_get_break_time());
cJSON_AddBoolToObject(root, "socketLockDetectionHigh", socket_lock_is_detection_high());
cJSON_AddNumberToObject(root, "socketLockRetryCount", socket_lock_get_retry_count());
cJSON_AddStringToObject(root, "modelMeter", meter_model_to_str(meter_get_model()));
cJSON_AddNumberToObject(root, "maxGridCurrent", grid_get_max_current());
cJSON_AddStringToObject(root, "stateMeter", meter_state_to_str(meter_get_state()));
char str[64];
cJSON_AddBoolToObject(root, "enabledocpp", ocpp_get_enabled());
ocpp_get_server(str);
cJSON_AddStringToObject(root, "serverocpp", str);
ocpp_get_rfid(str);
cJSON_AddStringToObject(root, "rfid", str);
return root;
}
esp_err_t json_set_evse_config(cJSON *root)
{
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "maxChargingCurrent")))
{
RETURN_ON_ERROR(evse_set_max_charging_current(cJSON_GetObjectItem(root, "maxChargingCurrent")->valuedouble));
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "chargingCurrent")))
{
RETURN_ON_ERROR(evse_set_charging_current(cJSON_GetObjectItem(root, "chargingCurrent")->valuedouble * 10));
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "defaultChargingCurrent")))
{
RETURN_ON_ERROR(evse_set_default_charging_current(cJSON_GetObjectItem(root, "defaultChargingCurrent")->valuedouble * 10));
}
if (cJSON_IsBool(cJSON_GetObjectItem(root, "requireAuth")))
{
evse_set_require_auth(cJSON_IsTrue(cJSON_GetObjectItem(root, "requireAuth")));
}
if (cJSON_IsBool(cJSON_GetObjectItem(root, "socketOutlet")))
{
RETURN_ON_ERROR(evse_set_socket_outlet(cJSON_IsTrue(cJSON_GetObjectItem(root, "socketOutlet"))));
}
if (cJSON_IsBool(cJSON_GetObjectItem(root, "rcm")))
{
RETURN_ON_ERROR(evse_set_rcm(cJSON_IsTrue(cJSON_GetObjectItem(root, "rcm"))));
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "temperatureThreshold")))
{
RETURN_ON_ERROR(evse_set_temp_threshold(cJSON_GetObjectItem(root, "temperatureThreshold")->valuedouble));
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "consumptionLimit")))
{
evse_set_consumption_limit(cJSON_GetObjectItem(root, "consumptionLimit")->valuedouble);
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "defaultConsumptionLimit")))
{
evse_set_default_consumption_limit(cJSON_GetObjectItem(root, "defaultConsumptionLimit")->valuedouble);
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "chargingTimeLimit")))
{
evse_set_charging_time_limit(cJSON_GetObjectItem(root, "chargingTimeLimit")->valuedouble);
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "defaultChargingTimeLimit")))
{
evse_set_default_charging_time_limit(cJSON_GetObjectItem(root, "defaultChargingTimeLimit")->valuedouble);
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "underPowerLimit")))
{
evse_set_under_power_limit(cJSON_GetObjectItem(root, "underPowerLimit")->valuedouble);
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "defaultUnderPowerLimit")))
{
evse_set_default_under_power_limit(cJSON_GetObjectItem(root, "defaultUnderPowerLimit")->valuedouble);
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "socketLockOperatingTime")))
{
RETURN_ON_ERROR(socket_lock_set_operating_time(cJSON_GetObjectItem(root, "socketLockOperatingTime")->valuedouble));
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "socketLockBreakTime")))
{
RETURN_ON_ERROR(socket_lock_set_break_time(cJSON_GetObjectItem(root, "socketLockBreakTime")->valuedouble));
}
if (cJSON_IsBool(cJSON_GetObjectItem(root, "socketLockDetectionHigh")))
{
socket_lock_set_detection_high(cJSON_IsTrue(cJSON_GetObjectItem(root, "socketLockDetectionHigh")));
}
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "socketLockRetryCount")))
{
socket_lock_set_retry_count(cJSON_GetObjectItem(root, "socketLockRetryCount")->valuedouble);
}
if (cJSON_IsString(cJSON_GetObjectItem(root, "modelMeter")))
{
RETURN_ON_ERROR(meter_set_model(meter_str_to_model(cJSON_GetObjectItem(root, "modelMeter")->valuestring)));
}
/*
if (cJSON_IsString(cJSON_GetObjectItem(root, "stateMeter")))
{
RETURN_ON_ERROR(meter_set_state(meter_str_to_state(cJSON_GetObjectItem(root, "stateMeter")->valuestring)));
}
*/
if (cJSON_IsNumber(cJSON_GetObjectItem(root, "maxGridCurrent")))
{
RETURN_ON_ERROR(grid_set_max_current(cJSON_GetObjectItem(root, "maxGridCurrent")->valuedouble));
}
if (cJSON_IsBool(cJSON_GetObjectItem(root, "enabledocpp")))
{
ocpp_set_enabled(cJSON_IsTrue(cJSON_GetObjectItem(root, "enabledocpp")));
}
if (cJSON_IsString(cJSON_GetObjectItem(root, "serverocpp")))
{
ocpp_set_server(cJSON_GetStringValue(cJSON_GetObjectItem(root, "serverocpp")));
}
if (cJSON_IsString(cJSON_GetObjectItem(root, "rfid")))
{
ocpp_set_rfid(cJSON_GetStringValue(cJSON_GetObjectItem(root, "rfid")));
}
return ESP_OK;
}
cJSON *json_get_wifi_config(void)
{
cJSON *root = cJSON_CreateObject();
char str[32];
cJSON_AddBoolToObject(root, "enabled", wifi_get_enabled());
wifi_get_ssid(str);
cJSON_AddStringToObject(root, "ssid", str);
return root;
}
esp_err_t json_set_wifi_config(cJSON *root, bool timeout)
{
bool enabled = cJSON_IsTrue(cJSON_GetObjectItem(root, "enabled"));
char *ssid = cJSON_GetStringValue(cJSON_GetObjectItem(root, "ssid"));
char *password = cJSON_GetStringValue(cJSON_GetObjectItem(root, "password"));
if (timeout)
{
return timeout_wifi_set_config(enabled, ssid, password);
}
else
{
return wifi_set_config(enabled, ssid, password);
}
}
cJSON *json_get_wifi_scan(void)
{
cJSON *root = cJSON_CreateArray();
wifi_scan_ap_t scan_aps[WIFI_SCAN_SCAN_LIST_SIZE];
uint16_t number = wifi_scan(scan_aps);
for (int i = 0; i < number; i++)
{
cJSON *item = cJSON_CreateObject();
cJSON_AddStringToObject(item, "ssid", scan_aps[i].ssid);
cJSON_AddNumberToObject(item, "rssi", scan_aps[i].rssi);
cJSON_AddBoolToObject(item, "auth", scan_aps[i].auth);
cJSON_AddItemToArray(root, item);
}
return root;
}
cJSON *json_get_mqtt_config(void)
{
cJSON *root = cJSON_CreateObject();
char str[64];
cJSON_AddBoolToObject(root, "enabled", mqtt_get_enabled());
mqtt_get_server(str);
cJSON_AddStringToObject(root, "server", str);
mqtt_get_base_topic(str);
cJSON_AddStringToObject(root, "baseTopic", str);
mqtt_get_user(str);
cJSON_AddStringToObject(root, "user", str);
mqtt_get_password(str);
cJSON_AddStringToObject(root, "password", str);
cJSON_AddNumberToObject(root, "periodicity", mqtt_get_periodicity());
return root;
}
esp_err_t json_set_mqtt_config(cJSON *root)
{
bool enabled = cJSON_IsTrue(cJSON_GetObjectItem(root, "enabled"));
char *server = cJSON_GetStringValue(cJSON_GetObjectItem(root, "server"));
char *base_topic = cJSON_GetStringValue(cJSON_GetObjectItem(root, "baseTopic"));
char *user = cJSON_GetStringValue(cJSON_GetObjectItem(root, "user"));
char *password = cJSON_GetStringValue(cJSON_GetObjectItem(root, "password"));
uint16_t periodicity = cJSON_GetNumberValue(cJSON_GetObjectItem(root, "periodicity"));
return mqtt_set_config(enabled, server, base_topic, user, password, periodicity);
}
cJSON *json_get_modbus_config(void)
{
cJSON *root = cJSON_CreateObject();
//cJSON_AddBoolToObject(root, "tcpEnabled", modbus_tcp_is_enabled());
//cJSON_AddNumberToObject(root, "unitId", modbus_get_unit_id());
cJSON_AddBoolToObject(root, "tcpEnabled", false);
cJSON_AddNumberToObject(root, "unitId", 1);
return root;
}
esp_err_t json_set_modbus_config(cJSON *root)
{
//bool tcp_enabled = cJSON_IsTrue(cJSON_GetObjectItem(root, "tcpEnabled"));
//uint8_t unit_id = cJSON_GetObjectItem(root, "unitId")->valuedouble;
//modbus_tcp_set_enabled(tcp_enabled);
return 0; //modbus_set_unit_id(unit_id);
}
/*
cJSON* json_get_script_config(void)
{
cJSON* root = cJSON_CreateObject();
cJSON_AddBoolToObject(root, "enabled", script_is_enabled());
return root;
}
esp_err_t json_set_script_config(cJSON* root)
{
bool enabled = cJSON_IsTrue(cJSON_GetObjectItem(root, "enabled"));
script_set_enabled(enabled);
return ESP_OK;
}*/
cJSON *json_get_time_config(void)
{
cJSON *root = cJSON_CreateObject();
char str[64];
cJSON_AddBoolToObject(root, "ntpEnabled", date_time_is_ntp_enabled());
date_time_get_ntp_server(str);
cJSON_AddStringToObject(root, "ntpServer", str);
cJSON_AddBoolToObject(root, "ntpFromDhcp", date_time_is_ntp_from_dhcp());
date_time_get_timezone(str);
cJSON_AddStringToObject(root, "timezone", str);
return root;
}
esp_err_t json_set_time_config(cJSON *root)
{
char *ntp_server = cJSON_GetStringValue(cJSON_GetObjectItem(root, "ntpServer"));
bool ntp_enabled = cJSON_IsTrue(cJSON_GetObjectItem(root, "ntpEnabled"));
bool ntp_from_dhcp = cJSON_IsTrue(cJSON_GetObjectItem(root, "ntpFromDhcp"));
char *timezone = cJSON_GetStringValue(cJSON_GetObjectItem(root, "timezone"));
date_time_set_ntp_config(ntp_enabled, ntp_server, ntp_from_dhcp);
return date_time_set_timezone(timezone);
}
cJSON *json_get_state(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "state", evse_state_to_str(evse_get_state()));
cJSON_AddBoolToObject(root, "available", evse_is_available());
cJSON_AddBoolToObject(root, "enabled", evse_is_enabled());
cJSON_AddBoolToObject(root, "pendingAuth", evse_is_pending_auth());
cJSON_AddBoolToObject(root, "limitReached", evse_is_limit_reached());
uint32_t error = evse_error_get_bits();
if (error == 0)
{
cJSON_AddNullToObject(root, "errors");
}
else
{
cJSON *errors = cJSON_CreateArray();
if (error & EVSE_ERR_PILOT_FAULT_BIT)
{
cJSON_AddItemToArray(errors, cJSON_CreateString("pilot_fault"));
}
if (error & EVSE_ERR_DIODE_SHORT_BIT)
{
cJSON_AddItemToArray(errors, cJSON_CreateString("diode_short"));
}
if (error & EVSE_ERR_LOCK_FAULT_BIT)
{
cJSON_AddItemToArray(errors, cJSON_CreateString("lock_fault"));
}
if (error & EVSE_ERR_UNLOCK_FAULT_BIT)
{
cJSON_AddItemToArray(errors, cJSON_CreateString("unlock_fault"));
}
if (error & EVSE_ERR_RCM_TRIGGERED_BIT)
{
cJSON_AddItemToArray(errors, cJSON_CreateString("rcm_triggered"));
}
if (error & EVSE_ERR_RCM_SELFTEST_FAULT_BIT)
{
cJSON_AddItemToArray(errors, cJSON_CreateString("rcm_selftest_fault"));
}
if (error & EVSE_ERR_TEMPERATURE_HIGH_BIT)
{
cJSON_AddItemToArray(errors, cJSON_CreateString("temperature_high"));
}
if (error & EVSE_ERR_TEMPERATURE_FAULT_BIT)
{
cJSON_AddItemToArray(errors, cJSON_CreateString("temperature_fault"));
}
cJSON_AddItemToObject(root, "errors", errors);
}
cJSON_AddNumberToObject(root, "sessionTime", energy_meter_get_session_time());
cJSON_AddNumberToObject(root, "chargingTime", energy_meter_get_charging_time());
cJSON_AddNumberToObject(root, "consumption", energy_meter_get_consumption());
cJSON_AddNumberToObject(root, "power", energy_meter_get_power());
float values[3];
energy_meter_get_voltage(values);
cJSON_AddItemToObject(root, "voltage", cJSON_CreateFloatArray(values, 3));
energy_meter_get_current(values);
cJSON_AddItemToObject(root, "current", cJSON_CreateFloatArray(values, 3));
return root;
}
cJSON *json_get_info(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_AddNumberToObject(root, "uptime", esp_timer_get_time() / 1000000);
const esp_app_desc_t *app_desc = esp_app_get_description();
cJSON_AddStringToObject(root, "appVersion", app_desc->version);
cJSON_AddStringToObject(root, "appDate", app_desc->date);
cJSON_AddStringToObject(root, "appTime", app_desc->time);
cJSON_AddStringToObject(root, "idfVersion", app_desc->idf_ver);
cJSON_AddStringToObject(root, "chip", CONFIG_IDF_TARGET);
esp_chip_info_t chip_info;
esp_chip_info(&chip_info);
cJSON_AddNumberToObject(root, "chipCores", chip_info.cores);
chip_info.revision = 301;
cJSON_AddNumberToObject(root, "chipRevision", chip_info.revision / 100);
multi_heap_info_t heap_info;
heap_caps_get_info(&heap_info, MALLOC_CAP_INTERNAL);
cJSON_AddNumberToObject(root, "heapSize", heap_info.total_allocated_bytes);
cJSON_AddNumberToObject(root, "maxHeapSize", heap_info.total_free_bytes + heap_info.total_allocated_bytes);
uint8_t mac[6];
char str[32];
esp_wifi_get_mac(ESP_IF_WIFI_STA, mac);
sprintf(str, MACSTR, MAC2STR(mac));
cJSON_AddStringToObject(root, "mac", str);
esp_netif_ip_info_t ip_info;
esp_netif_get_ip_info(esp_netif_get_handle_from_ifkey("WIFI_STA_DEF"), &ip_info);
esp_ip4addr_ntoa(&ip_info.ip, str, sizeof(str));
cJSON_AddStringToObject(root, "ip", str);
esp_wifi_get_mac(ESP_IF_WIFI_AP, mac);
sprintf(str, MACSTR, MAC2STR(mac));
cJSON_AddStringToObject(root, "macAp", str);
esp_netif_get_ip_info(esp_netif_get_handle_from_ifkey("WIFI_AP_DEF"), &ip_info);
esp_ip4addr_ntoa(&ip_info.ip, str, sizeof(str));
cJSON_AddStringToObject(root, "ipAp", str);
cJSON_AddNumberToObject(root, "temperatureSensorCount", temp_sensor_get_count());
cJSON_AddNumberToObject(root, "temperatureLow", temp_sensor_get_low() / 100.0);
cJSON_AddNumberToObject(root, "temperatureHigh", temp_sensor_get_high() / 100.0);
return root;
}
static const char *serial_to_str(board_config_serial_t serial)
{
switch (serial)
{
case BOARD_CONFIG_SERIAL_UART:
return "uart";
case BOARD_CONFIG_SERIAL_RS485:
return "rs485";
default:
return "none";
}
}
cJSON *json_get_board_config(void)
{
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "deviceName", board_config.device_name);
cJSON_AddBoolToObject(root, "socketLock", board_config.socket_lock);
cJSON_AddBoolToObject(root, "proximity", board_config.proximity);
cJSON_AddNumberToObject(root, "socketLockMinBreakTime", board_config.socket_lock_min_break_time);
cJSON_AddBoolToObject(root, "rcm", board_config.rcm);
cJSON_AddBoolToObject(root, "temperatureSensor", board_config.onewire && board_config.onewire_temp_sensor);
switch (board_config.energy_meter)
{
case BOARD_CONFIG_ENERGY_METER_CUR:
cJSON_AddStringToObject(root, "energyMeter", "cur");
break;
case BOARD_CONFIG_ENERGY_METER_CUR_VLT:
cJSON_AddStringToObject(root, "energyMeter", "cur_vlt");
break;
default:
cJSON_AddStringToObject(root, "energyMeter", "none");
}
cJSON_AddBoolToObject(root, "energyMeterThreePhases", board_config.energy_meter_three_phases);
cJSON_AddStringToObject(root, "serial1", serial_to_str(board_config.serial_1));
cJSON_AddStringToObject(root, "serial1Name", board_config.serial_1_name);
cJSON_AddStringToObject(root, "serial2", serial_to_str(board_config.serial_2));
cJSON_AddStringToObject(root, "serial2Name", board_config.serial_2_name);
#if SOC_UART_NUM > 2
cJSON_AddStringToObject(root, "serial3", serial_to_str(board_config.serial_3));
cJSON_AddStringToObject(root, "serial3Name", board_config.serial_3_name);
#else
cJSON_AddStringToObject(root, "serial3", serial_to_str(BOARD_CONFIG_SERIAL_NONE));
cJSON_AddStringToObject(root, "serial3Name", "");
#endif
cJSON *aux = cJSON_CreateArray();
if (board_config.aux_in_1)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_in_1_name));
}
if (board_config.aux_in_2)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_in_2_name));
}
if (board_config.aux_in_3)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_in_3_name));
}
if (board_config.aux_in_4)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_in_4_name));
}
cJSON_AddItemToObject(root, "auxIn", aux);
aux = cJSON_CreateArray();
if (board_config.aux_out_1)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_out_1_name));
}
if (board_config.aux_out_2)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_out_2_name));
}
if (board_config.aux_out_3)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_out_3_name));
}
if (board_config.aux_out_4)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_out_4_name));
}
cJSON_AddItemToObject(root, "auxOut", aux);
aux = cJSON_CreateArray();
if (board_config.aux_ain_1)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_ain_1_name));
}
if (board_config.aux_ain_2)
{
cJSON_AddItemToArray(aux, cJSON_CreateString(board_config.aux_ain_2_name));
}
cJSON_AddItemToObject(root, "auxAin", aux);
return root;
}

66
components/api/src/ota.c Executable file
View File

@@ -0,0 +1,66 @@
#include <string.h>
#include "esp_log.h"
#include "esp_err.h"
#include "esp_http_client.h"
#include "cJSON.h"
#include "ota.h"
static const char* TAG = "ota";
extern const char server_cert_pem_start[] asm("_binary_ca_cert_pem_start");
extern const char server_cert_pem_end[] asm("_binary_ca_cert_pem_end");
static void http_client_cleanup(esp_http_client_handle_t client)
{
esp_http_client_close(client);
esp_http_client_cleanup(client);
}
esp_err_t ota_get_available_version(char* version)
{
esp_http_client_config_t config = {
.url = OTA_VERSION_URL,
.cert_pem = server_cert_pem_start
};
esp_http_client_handle_t client = esp_http_client_init(&config);
esp_err_t err = esp_http_client_open(client, 0);
if (err != ESP_OK) {
ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
esp_http_client_cleanup(client);
return err;
}
int content_length = esp_http_client_fetch_headers(client);
if (content_length > 0) {
esp_http_client_read(client, version, content_length);
version[content_length] = '\0';
http_client_cleanup(client);
return ESP_OK;
} else {
http_client_cleanup(client);
ESP_LOGI(TAG, "No firmware available");
return ESP_ERR_NOT_FOUND;
}
}
bool ota_is_newer_version(const char* actual, const char* available)
{
// available version has no suffix eg: vX.X.X-beta
char actual_trimed[32];
strcpy(actual_trimed, actual);
char* saveptr;
strtok_r(actual_trimed, "-", &saveptr);
bool actual_has_suffix = strtok_r(NULL, "-", &saveptr);
int diff = strcmp(available, actual_trimed);
if (diff == 0) {
return actual_has_suffix;
} else {
return diff > 0;
}
}

View File

@@ -0,0 +1,74 @@
#include <string.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_system.h"
#include "timeout_utils.h"
#include "wifi.h"
#include "rest.h"
static void restart_func(void* arg)
{
vTaskDelay(pdMS_TO_TICKS(5000));
esp_restart();
vTaskDelete(NULL);
}
void timeout_restart()
{
xTaskCreate(restart_func, "restart_task", 2 * 1024, NULL, 10, NULL);
}
typedef struct
{
bool enabled;
bool ssid_blank;
char ssid[32];
bool password_blank;
char password[64];
} wifi_set_config_arg_t;
static void wifi_set_config_func(void* arg)
{
vTaskDelay(pdMS_TO_TICKS(1000));
wifi_set_config_arg_t* config = (wifi_set_config_arg_t*)arg;
wifi_set_config(config->enabled, config->ssid_blank ? NULL : config->ssid, config->password_blank ? NULL : config->password);
free((void*)config);
vTaskDelete(NULL);
}
esp_err_t timeout_wifi_set_config(bool enabled, const char* ssid, const char* password)
{
if (enabled) {
if (ssid == NULL || strlen(ssid) == 0) {
char old_ssid[32];
wifi_get_ssid(old_ssid);
if (strlen(old_ssid) == 0) {
return ESP_ERR_INVALID_ARG;
}
}
}
wifi_set_config_arg_t* config = (wifi_set_config_arg_t*)malloc(sizeof(wifi_set_config_arg_t));
config->enabled = enabled;
if (ssid == NULL || ssid[0] == '\0') {
config->ssid_blank = true;
} else {
config->ssid_blank = false;
strcpy(config->ssid, ssid);
}
if (password == NULL || password[0] == '\0') {
config->password_blank = true;
} else {
config->password_blank = false;
strcpy(config->password, password);
}
xTaskCreate(wifi_set_config_func, "wifi_set_config", 4 * 1024, (void*)config, 10, NULL);
return ESP_OK;
}

View File

@@ -0,0 +1,6 @@
set(srcs
"board_config.c")
idf_component_register(SRCS "${srcs}"
PRIV_REQUIRES nvs_flash
INCLUDE_DIRS "include")

209
components/config/board_config.c Executable file
View File

@@ -0,0 +1,209 @@
#include <string.h>
#include <ctype.h>
#include "esp_system.h"
#include "esp_log.h"
#include "esp_err.h"
#include "board_config.h"
static const char *TAG = "board_config";
board_config_t board_config;
bool atob(const char *value)
{
return value[0] == 'y';
}
board_config_energy_meter_t atoem(const char *value)
{
if (!strcmp(value, "cur"))
{
return BOARD_CONFIG_ENERGY_METER_CUR;
}
if (!strcmp(value, "cur_vlt"))
{
return BOARD_CONFIG_ENERGY_METER_CUR_VLT;
}
return BOARD_CONFIG_ENERGY_METER_NONE;
}
board_config_serial_t atoser(const char *value)
{
if (!strcmp(value, "uart"))
{
return BOARD_CONFIG_SERIAL_UART;
}
if (!strcmp(value, "rs485"))
{
return BOARD_CONFIG_SERIAL_RS485;
}
return BOARD_CONFIG_SERIAL_NONE;
}
#define SET_CONFIG_VALUE(name, prop, convert_fn) \
if (!strcmp(key, name)) \
{ \
board_config.prop = convert_fn(value); \
continue; \
}
#define SET_CONFIG_VALUE_STR(name, prop) \
if (!strcmp(key, name)) \
{ \
strcpy(board_config.prop, value); \
continue; \
}
void board_config_load()
{
memset(&board_config, 0, sizeof(board_config_t));
FILE *file = fopen("/cfg/board.cfg", "r");
if (file == NULL)
{
ESP_ERROR_CHECK(ESP_ERR_NOT_FOUND);
}
char buffer[256];
while (fgets(buffer, 256, file))
{
int buf_length = strlen(buffer);
int buf_start = 0;
while (buf_start < buf_length && isspace((unsigned char)buffer[buf_start]))
{
buf_start++;
}
int buf_end = buf_length;
while (buf_end > 0 && !isgraph((unsigned char)buffer[buf_end - 1]))
{
buf_end--;
}
buffer[buf_end] = '\0';
char *line = &buffer[buf_start];
if (line[0] != '#')
{
char *saveptr;
char *key = strtok_r(line, "=", &saveptr);
if (key != NULL)
{
char *value = strtok_r(NULL, "=", &saveptr);
if (value != NULL)
{
SET_CONFIG_VALUE_STR("DEVICE_NAME", device_name);
SET_CONFIG_VALUE("LED_CHARGING", led_charging, atob);
SET_CONFIG_VALUE("LED_CHARGING_GPIO", led_charging_gpio, atoi);
SET_CONFIG_VALUE("LED_ERROR", led_error, atob);
SET_CONFIG_VALUE("LED_ERROR_GPIO", led_error_gpio, atoi);
SET_CONFIG_VALUE("LED_STOP", led_stop, atob);
SET_CONFIG_VALUE("LED_STOP_GPIO", led_stop_gpio, atoi);
SET_CONFIG_VALUE("BUZZER", buzzer, atob);
SET_CONFIG_VALUE("BUZZER_GPIO", buzzer_gpio, atoi);
SET_CONFIG_VALUE("BUTTON_WIFI_GPIO", button_wifi_gpio, atoi);
SET_CONFIG_VALUE("PILOT_PWM_GPIO", pilot_pwm_gpio, atoi);
SET_CONFIG_VALUE("PILOT_ADC_CHANNEL", pilot_adc_channel, atoi);
SET_CONFIG_VALUE("PILOT_DOWN_THRESHOLD_12", pilot_down_threshold_12, atoi);
SET_CONFIG_VALUE("PILOT_DOWN_THRESHOLD_9", pilot_down_threshold_9, atoi);
SET_CONFIG_VALUE("PILOT_DOWN_THRESHOLD_6", pilot_down_threshold_6, atoi);
SET_CONFIG_VALUE("PILOT_DOWN_THRESHOLD_3", pilot_down_threshold_3, atoi);
SET_CONFIG_VALUE("PILOT_DOWN_THRESHOLD_N12", pilot_down_threshold_n12, atoi);
SET_CONFIG_VALUE("PROXIMITY", proximity, atob);
SET_CONFIG_VALUE("PROXIMITY_ADC_CHANNEL", proximity_adc_channel, atoi);
SET_CONFIG_VALUE("PROXIMITY_DOWN_THRESHOLD_8", proximity_down_threshold_8, atoi);
SET_CONFIG_VALUE("PROXIMITY_DOWN_THRESHOLD_10", proximity_down_threshold_10, atoi);
SET_CONFIG_VALUE("PROXIMITY_DOWN_THRESHOLD_13", proximity_down_threshold_13, atoi);
SET_CONFIG_VALUE("PROXIMITY_DOWN_THRESHOLD_20", proximity_down_threshold_20, atoi);
SET_CONFIG_VALUE("PROXIMITY_DOWN_THRESHOLD_25", proximity_down_threshold_25, atoi);
SET_CONFIG_VALUE("PROXIMITY_DOWN_THRESHOLD_32", proximity_down_threshold_32, atoi);
SET_CONFIG_VALUE("AC_RELAY_GPIO", ac_relay_gpio, atoi);
SET_CONFIG_VALUE("SOCKET_LOCK", socket_lock, atob);
SET_CONFIG_VALUE("SOCKET_LOCK_A_GPIO", socket_lock_a_gpio, atoi);
SET_CONFIG_VALUE("SOCKET_LOCK_B_GPIO", socket_lock_b_gpio, atoi);
SET_CONFIG_VALUE("SOCKET_LOCK_DETECTION_GPIO", socket_lock_detection_gpio, atoi);
SET_CONFIG_VALUE("SOCKET_LOCK_DETECTION_DELAY", socket_lock_detection_delay, atoi);
SET_CONFIG_VALUE("SOCKET_LOCK_MIN_BREAK_TIME", socket_lock_min_break_time, atoi);
SET_CONFIG_VALUE("RCM", rcm, atob);
SET_CONFIG_VALUE("RCM_GPIO", rcm_gpio, atoi);
SET_CONFIG_VALUE("RCM_TEST_GPIO", rcm_test_gpio, atoi);
SET_CONFIG_VALUE("ENERGY_METER", energy_meter, atoem);
SET_CONFIG_VALUE("ENERGY_METER_THREE_PHASES", energy_meter_three_phases, atob);
SET_CONFIG_VALUE("ENERGY_METER_L1_CUR_ADC_CHANNEL", energy_meter_l1_cur_adc_channel, atoi);
SET_CONFIG_VALUE("ENERGY_METER_L2_CUR_ADC_CHANNEL", energy_meter_l2_cur_adc_channel, atoi);
SET_CONFIG_VALUE("ENERGY_METER_L3_CUR_ADC_CHANNEL", energy_meter_l3_cur_adc_channel, atoi);
SET_CONFIG_VALUE("ENERGY_METER_CUR_SCALE", energy_meter_cur_scale, atoff);
SET_CONFIG_VALUE("ENERGY_METER_L1_VLT_ADC_CHANNEL", energy_meter_l1_vlt_adc_channel, atoi);
SET_CONFIG_VALUE("ENERGY_METER_L2_VLT_ADC_CHANNEL", energy_meter_l2_vlt_adc_channel, atoi);
SET_CONFIG_VALUE("ENERGY_METER_L3_VLT_ADC_CHANNEL", energy_meter_l3_vlt_adc_channel, atoi);
SET_CONFIG_VALUE("ENERGY_METER_VLT_SCALE", energy_meter_vlt_scale, atoff);
SET_CONFIG_VALUE("AUX_IN_1", aux_in_1, atob);
SET_CONFIG_VALUE_STR("AUX_IN_1_NAME", aux_in_1_name);
SET_CONFIG_VALUE("AUX_IN_1_GPIO", aux_in_1_gpio, atoi);
SET_CONFIG_VALUE("AUX_IN_2", aux_in_2, atob);
SET_CONFIG_VALUE_STR("AUX_IN_2_NAME", aux_in_2_name);
SET_CONFIG_VALUE("AUX_IN_2_GPIO", aux_in_2_gpio, atoi);
SET_CONFIG_VALUE("AUX_IN_3", aux_in_3, atob);
SET_CONFIG_VALUE_STR("AUX_IN_3_NAME", aux_in_3_name);
SET_CONFIG_VALUE("AUX_IN_3_GPIO", aux_in_3_gpio, atoi);
SET_CONFIG_VALUE("AUX_IN_4", aux_in_4, atob);
SET_CONFIG_VALUE_STR("AUX_IN_4_NAME", aux_in_4_name);
SET_CONFIG_VALUE("AUX_IN_4_GPIO", aux_in_4_gpio, atoi);
SET_CONFIG_VALUE("AUX_OUT_1", aux_out_1, atob);
SET_CONFIG_VALUE_STR("AUX_OUT_1_NAME", aux_out_1_name);
SET_CONFIG_VALUE("AUX_OUT_1_GPIO", aux_out_1_gpio, atoi);
SET_CONFIG_VALUE("AUX_OUT_2", aux_out_2, atob);
SET_CONFIG_VALUE_STR("AUX_OUT_2_NAME", aux_out_2_name);
SET_CONFIG_VALUE("AUX_OUT_2_GPIO", aux_out_2_gpio, atoi);
SET_CONFIG_VALUE("AUX_OUT_3", aux_out_3, atob);
SET_CONFIG_VALUE_STR("AUX_OUT_3_NAME", aux_out_3_name);
SET_CONFIG_VALUE("AUX_OUT_3_GPIO", aux_out_3_gpio, atoi);
SET_CONFIG_VALUE("AUX_OUT_4", aux_out_4, atob);
SET_CONFIG_VALUE_STR("AUX_OUT_4_NAME", aux_out_4_name);
SET_CONFIG_VALUE("AUX_OUT_4_GPIO", aux_out_4_gpio, atoi);
SET_CONFIG_VALUE("AUX_AIN_1", aux_ain_1, atob);
SET_CONFIG_VALUE_STR("AUX_AIN_1_NAME", aux_ain_1_name);
SET_CONFIG_VALUE("AUX_AIN_1_ADC_CHANNEL", aux_ain_1_adc_channel, atoi);
SET_CONFIG_VALUE("AUX_AIN_2", aux_ain_2, atob);
SET_CONFIG_VALUE_STR("AUX_AIN_2_NAME", aux_ain_2_name);
SET_CONFIG_VALUE("AUX_AIN_2_ADC_CHANNEL", aux_ain_2_adc_channel, atoi);
/*
#if CONFIG_ESP_CONSOLE_UART_NUM != 0
SET_CONFIG_VALUE("SERIAL_1", serial_1, atoser);
SET_CONFIG_VALUE_STR("SERIAL_1_NAME", serial_1_name);
SET_CONFIG_VALUE("SERIAL_1_RXD_GPIO", serial_1_rxd_gpio, atoi);
SET_CONFIG_VALUE("SERIAL_1_TXD_GPIO", serial_1_txd_gpio, atoi);
SET_CONFIG_VALUE("SERIAL_1_RTS_GPIO", serial_1_rts_gpio, atoi);
#endif // CONFIG_ESP_CONSOLE_UART_NUM != 0
#if CONFIG_ESP_CONSOLE_UART_NUM != 1
SET_CONFIG_VALUE("SERIAL_2", serial_2, atoser);
SET_CONFIG_VALUE_STR("SERIAL_2_NAME", serial_2_name);
SET_CONFIG_VALUE("SERIAL_2_RXD_GPIO", serial_2_rxd_gpio, atoi);
SET_CONFIG_VALUE("SERIAL_2_TXD_GPIO", serial_2_txd_gpio, atoi);
SET_CONFIG_VALUE("SERIAL_2_RTS_GPIO", serial_2_rts_gpio, atoi);
#endif // CONFIG_ESP_CONSOLE_UART_NUM != 1
#if SOC_UART_NUM > 2
#if CONFIG_ESP_CONSOLE_UART_NUM != 2
SET_CONFIG_VALUE("SERIAL_3", serial_3, atoser);
SET_CONFIG_VALUE_STR("SERIAL_3_NAME", serial_3_name);
SET_CONFIG_VALUE("SERIAL_3_RXD_GPIO", serial_3_rxd_gpio, atoi);
SET_CONFIG_VALUE("SERIAL_3_TXD_GPIO", serial_3_txd_gpio, atoi);
SET_CONFIG_VALUE("SERIAL_3_RTS_GPIO", serial_3_rts_gpio, atoi);
#endif / CONFIG_ESP_CONSOLE_UART_NUM != 2
#endif // SOC_UART_NUM > 2
SET_CONFIG_VALUE("ONEWIRE", onewire, atob);
SET_CONFIG_VALUE("ONEWIRE_GPIO", onewire_gpio, atoi);
SET_CONFIG_VALUE("ONEWIRE_TEMP_SENSOR", onewire_temp_sensor, atob);
ESP_LOGE(TAG, "Unknown config value %s=%s", key, value);
*/
}
}
}
}
fclose(file);
}

View File

@@ -0,0 +1,146 @@
#ifndef BOARD_CONFIG_H_
#define BOARD_CONFIG_H_
#include "hal/adc_types.h"
#include "hal/gpio_types.h"
#include "soc/soc_caps.h"
typedef enum {
BOARD_CONFIG_ENERGY_METER_NONE,
BOARD_CONFIG_ENERGY_METER_CUR,
BOARD_CONFIG_ENERGY_METER_CUR_VLT
} board_config_energy_meter_t;
typedef enum {
BOARD_CONFIG_SERIAL_NONE,
BOARD_CONFIG_SERIAL_UART,
BOARD_CONFIG_SERIAL_RS485
} board_config_serial_t;
typedef struct
{
char device_name[32];
bool led_charging : 1;
gpio_num_t led_charging_gpio;
bool led_error : 1;
gpio_num_t led_error_gpio;
bool led_stop : 1;
gpio_num_t led_stop_gpio;
bool buzzer : 1;
gpio_num_t buzzer_gpio;
gpio_num_t button_wifi_gpio;
gpio_num_t pilot_pwm_gpio;
adc_channel_t pilot_adc_channel;
uint16_t pilot_down_threshold_12;
uint16_t pilot_down_threshold_9;
uint16_t pilot_down_threshold_6;
uint16_t pilot_down_threshold_3;
uint16_t pilot_down_threshold_n12;
bool proximity : 1;
adc_channel_t proximity_adc_channel;
uint16_t proximity_down_threshold_8;
uint16_t proximity_down_threshold_10;
uint16_t proximity_down_threshold_13;
uint16_t proximity_down_threshold_20;
uint16_t proximity_down_threshold_25;
uint16_t proximity_down_threshold_32;
gpio_num_t ac_relay_gpio;
bool socket_lock : 1;
gpio_num_t socket_lock_a_gpio;
gpio_num_t socket_lock_b_gpio;
gpio_num_t socket_lock_detection_gpio;
uint16_t socket_lock_detection_delay;
uint16_t socket_lock_min_break_time;
bool rcm : 1;
gpio_num_t rcm_gpio;
gpio_num_t rcm_test_gpio;
board_config_energy_meter_t energy_meter;
bool energy_meter_three_phases : 1;
adc_channel_t energy_meter_l1_cur_adc_channel;
adc_channel_t energy_meter_l2_cur_adc_channel;
adc_channel_t energy_meter_l3_cur_adc_channel;
float energy_meter_cur_scale;
adc_channel_t energy_meter_l1_vlt_adc_channel;
adc_channel_t energy_meter_l2_vlt_adc_channel;
adc_channel_t energy_meter_l3_vlt_adc_channel;
float energy_meter_vlt_scale;
bool aux_in_1 : 1;
char aux_in_1_name[8];
gpio_num_t aux_in_1_gpio;
bool aux_in_2 : 1;
char aux_in_2_name[8];
gpio_num_t aux_in_2_gpio;
bool aux_in_3 : 1;
char aux_in_3_name[8];
gpio_num_t aux_in_3_gpio;
bool aux_in_4 : 1;
char aux_in_4_name[8];
gpio_num_t aux_in_4_gpio;
bool aux_out_1 : 1;
char aux_out_1_name[8];
gpio_num_t aux_out_1_gpio;
bool aux_out_2 : 1;
char aux_out_2_name[8];
gpio_num_t aux_out_2_gpio;
bool aux_out_3 : 1;
char aux_out_3_name[8];
gpio_num_t aux_out_3_gpio;
bool aux_out_4 : 1;
char aux_out_4_name[8];
gpio_num_t aux_out_4_gpio;
bool aux_ain_1 : 1;
char aux_ain_1_name[8];
adc_channel_t aux_ain_1_adc_channel;
bool aux_ain_2 : 1;
char aux_ain_2_name[8];
adc_channel_t aux_ain_2_adc_channel;
board_config_serial_t serial_1;
char serial_1_name[16];
gpio_num_t serial_1_rxd_gpio;
gpio_num_t serial_1_txd_gpio;
gpio_num_t serial_1_rts_gpio;
board_config_serial_t serial_2;
char serial_2_name[16];
gpio_num_t serial_2_rxd_gpio;
gpio_num_t serial_2_txd_gpio;
gpio_num_t serial_2_rts_gpio;
#if SOC_UART_NUM > 2
board_config_serial_t serial_3;
char serial_3_name[16];
gpio_num_t serial_3_rxd_gpio;
gpio_num_t serial_3_txd_gpio;
gpio_num_t serial_3_rts_gpio;
#endif /* SOC_UART_NUM > 2 */
bool onewire : 1;
gpio_num_t onewire_gpio;
bool onewire_temp_sensor : 1;
} board_config_t;
extern board_config_t board_config;
void board_config_load();
#endif /* BOARD_CONFIG_H_ */

View File

@@ -0,0 +1,9 @@
set(srcs
"src/input_filter.c"
"src/currentshaper.c"
)
idf_component_register(SRCS "${srcs}"
INCLUDE_DIRS "include"
PRIV_REQUIRES nvs_flash
REQUIRES config evse)

View File

@@ -0,0 +1,48 @@
#ifndef CURRENTSHAPER_H_
#define CURRENTSHAPER_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Inicia a tarefa do shaper de corrente dinâmica.
*/
void currentshaper_start(void);
/**
* @brief Encerra a tarefa do shaper de corrente dinâmica.
*/
void currentshaper_stop(void);
/**
* @brief Executa a lógica de modelagem da corrente com base nos dados atuais.
*/
void shapeCurrent(void);
/**
* @brief Define a corrente máxima disponível da rede elétrica (A*10).
*
* @param max_grid_current Corrente máxima da rede (em A*10)
*/
void setMaxGridCurrent(int max_grid_current);
/**
* @brief Define a corrente medida em tempo real disponível na rede (A*10).
*
* @param live_grid_current Corrente de rede ao vivo (em A*10)
*/
void setLiveGridCurrent(int live_grid_current);
/**
* @brief Define a tensão medida em tempo real da rede (V).
*
* @param live_volt Tensão da rede (em volts)
*/
void setLiveVolt(int live_volt);
#ifdef __cplusplus
}
#endif
#endif /* CURRENTSHAPER_H_ */

View File

@@ -0,0 +1,31 @@
#ifndef _INPUT_FILTER_H
#define _INPUT_FILTER_H
#include <stdint.h> // Necessário para uint32_t
#include <inttypes.h> // Para uso de PRIu32 se necessário em logs
// Constante mínima de tempo (tau), em milissegundos
#ifndef INPUT_FILTER_MIN_TAU
#define INPUT_FILTER_MIN_TAU 10 // ms
#endif
/**
* @brief Calcula o fator de suavização com base em delta e tau.
*
* @param delta Tempo desde a última atualização (ms)
* @param tau Constante de tempo do filtro (ms)
* @return double Fator de suavização (0.0 a 1.0)
*/
double getFactor(uint32_t delta, uint32_t tau);
/**
* @brief Aplica filtro exponencial a uma entrada.
*
* @param input Valor atual medido
* @param filtered Valor suavizado anterior
* @param tau Constante de tempo (ms)
* @return double Novo valor suavizado
*/
double filter(double input, double filtered, uint32_t tau);
#endif // _INPUT_FILTER_H

View File

@@ -0,0 +1,136 @@
// currentshaper.c
#include "esp_log.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <sys/param.h>
#include "evse_api.h"
#include "input_filter.h"
static const char *TAG = "currentshaper";
#define EVSE_SHAPER_HYSTERESIS 50 // A*10
#define CHARGING_CURRENT_MIN 60 // A*10
static TaskHandle_t currentshaper_task = NULL;
static uint32_t smoothing_time_ms = 1000;
static uint32_t min_pause_time_ms = 300000;
static uint32_t max_data_interval_ms = 120000;
static int max_grid_current = 300; // A*10
static int live_grid_current = 0; // A*10
static int live_voltage = 230;
static double smoothed_current = 0;
static uint16_t max_current = 0;
static TickType_t timer = 0;
static TickType_t pause_timer = 0;
static bool updated = false;
static bool changed = false;
static portMUX_TYPE mux = portMUX_INITIALIZER_UNLOCKED;
void shapeCurrent()
{
taskENTER_CRITICAL(&mux);
updated = true;
smoothed_current = filter(live_grid_current, smoothed_current, smoothing_time_ms);
int diff = max_grid_current - (int)smoothed_current;
int charge_current = evse_get_charging_current();
int new_current = diff + charge_current;
new_current = MIN(new_current, evse_get_max_charging_current() * 10);
new_current = MAX(new_current, CHARGING_CURRENT_MIN);
max_current = new_current;
if (charge_current != max_current)
{
evse_set_charging_current(max_current);
changed = true;
}
taskEXIT_CRITICAL(&mux);
}
void setMaxGridCurrent(int value)
{
taskENTER_CRITICAL(&mux);
max_grid_current = value;
taskEXIT_CRITICAL(&mux);
ESP_LOGI(TAG, "Max grid current: %d A*10", value);
}
void setLiveGridCurrent(int value)
{
taskENTER_CRITICAL(&mux);
live_grid_current = value;
taskEXIT_CRITICAL(&mux);
ESP_LOGI(TAG, "Live grid current: %d A*10", value);
if (evse_state_is_charging(evse_get_state()))
{
shapeCurrent();
}
}
void setLiveVoltage(int value)
{
taskENTER_CRITICAL(&mux);
live_voltage = value;
taskEXIT_CRITICAL(&mux);
ESP_LOGD(TAG, "Live voltage: %d V", value);
}
static void currentshaper_task_func(void *param)
{
while (true)
{
TickType_t now = xTaskGetTickCount();
if (evse_state_is_charging(evse_get_state()))
{
taskENTER_CRITICAL(&mux);
if (changed)
{
if (max_current < CHARGING_CURRENT_MIN)
{
evse_set_charging_current(CHARGING_CURRENT_MIN);
if (pause_timer == 0)
pause_timer = now;
}
else if ((pause_timer != 0) && (now - pause_timer) * portTICK_PERIOD_MS >= min_pause_time_ms &&
(max_current - CHARGING_CURRENT_MIN >= EVSE_SHAPER_HYSTERESIS))
{
pause_timer = 0;
}
timer = now;
changed = false;
}
else if (!updated || (now - timer) * portTICK_PERIOD_MS > max_data_interval_ms)
{
if (updated)
{
pause_timer = now;
updated = false;
smoothed_current = live_grid_current;
}
}
taskEXIT_CRITICAL(&mux);
}
vTaskDelay(pdMS_TO_TICKS(1000));
}
}
void currentshaper_start()
{
ESP_LOGI(TAG, "Starting current shaper task");
xTaskCreate(currentshaper_task_func, "currentshaper_task", 4096, NULL, 5, &currentshaper_task);
}
void currentshaper_stop()
{
ESP_LOGI(TAG, "Stopping current shaper task");
if (currentshaper_task != NULL)
{
vTaskDelete(currentshaper_task);
currentshaper_task = NULL;
}
}

View File

@@ -0,0 +1,36 @@
// input_filter.c
#include "input_filter.h"
#include "esp_log.h"
#include <math.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include <stdint.h>
static const char *TAG = "inputfilter";
static TickType_t last_data_time = 0;
#define MIN_TAU_MS 100 // Minimum time constant in ms
double getFactor(uint32_t delta_ms, uint32_t tau_ms)
{
if (tau_ms < MIN_TAU_MS)
{
tau_ms = MIN_TAU_MS;
}
double factor = 1.0 - exp(-((double)delta_ms / (double)tau_ms));
ESP_LOGD(TAG, "delta_ms=%" PRIu32 ", tau_ms=%" PRIu32 ", factor=%f", delta_ms, tau_ms, factor);
return factor;
}
double filter(double input, double filtered, uint32_t tau_ms)
{
TickType_t now = xTaskGetTickCount();
uint32_t delta_ms = (now - last_data_time) * portTICK_PERIOD_MS;
last_data_time = now;
double factor = getFactor(delta_ms, tau_ms);
filtered = input * factor + filtered * (1.0 - factor);
ESP_LOGD(TAG, "input=%f, filtered=%f", input, filtered);
return filtered;
}

View File

@@ -0,0 +1,20 @@
name: esp_idf_lib_helpers
description: Common support library for esp-idf-lib
version: 1.2.0
groups:
- common
code_owners:
- trombik
- UncleRus
depends:
- freertos
thread_safe: n/a
targets:
- esp32
- esp8266
- esp32s2
- esp32c3
license: ISC
copyrights:
- name: trombik
year: 2019

View File

@@ -0,0 +1,4 @@
idf_component_register(
INCLUDE_DIRS .
REQUIRES freertos
)

View File

@@ -0,0 +1,13 @@
Copyright (c) 2019 Tomoyuki Sakurai <y@trombik.org>
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

View File

@@ -0,0 +1,8 @@
COMPONENT_ADD_INCLUDEDIRS = .
ifdef CONFIG_IDF_TARGET_ESP8266
COMPONENT_DEPENDS = esp8266 freertos
else
COMPONENT_DEPENDS = freertos
endif

View File

@@ -0,0 +1,84 @@
/*
* Copyright (c) 2019 Tomoyuki Sakurai <y@trombik.org>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#if !defined(__ESP_IDF_LIB_HELPERS__H__)
#define __ESP_IDF_LIB_HELPERS__H__
/* XXX this header file does not need to include freertos/FreeRTOS.h.
* but without it, ESP8266 RTOS SDK does not include `sdkconfig.h` in correct
* order. as this header depends on sdkconfig.h, sdkconfig.h must be included
* first. however, the SDK includes this header first, then includes
* `sdkconfig.h` when freertos/FreeRTOS.h is not explicitly included. an
* evidence can be found in `build/${COMPONENT}/${COMPONENT}.d` in a failed
* build.
*/
#include <freertos/FreeRTOS.h>
#include <esp_idf_version.h>
#if !defined(ESP_IDF_VERSION) || !defined(ESP_IDF_VERSION_VAL)
#error Unknown ESP-IDF/ESP8266 RTOS SDK version
#endif
/* Minimal supported version for ESP32, ESP32S2 */
#define HELPER_ESP32_MIN_VER ESP_IDF_VERSION_VAL(3, 3, 5)
/* Minimal supported version for ESP8266 */
#define HELPER_ESP8266_MIN_VER ESP_IDF_VERSION_VAL(3, 3, 0)
/* HELPER_TARGET_IS_ESP32
* 1 when the target is esp32
*/
#if defined(CONFIG_IDF_TARGET_ESP32) \
|| defined(CONFIG_IDF_TARGET_ESP32S2) \
|| defined(CONFIG_IDF_TARGET_ESP32S3) \
|| defined(CONFIG_IDF_TARGET_ESP32C2) \
|| defined(CONFIG_IDF_TARGET_ESP32C3) \
|| defined(CONFIG_IDF_TARGET_ESP32C6) \
|| defined(CONFIG_IDF_TARGET_ESP32H2)
#define HELPER_TARGET_IS_ESP32 (1)
#define HELPER_TARGET_IS_ESP8266 (0)
/* HELPER_TARGET_IS_ESP8266
* 1 when the target is esp8266
*/
#elif defined(CONFIG_IDF_TARGET_ESP8266)
#define HELPER_TARGET_IS_ESP32 (0)
#define HELPER_TARGET_IS_ESP8266 (1)
#else
#error BUG: cannot determine the target
#endif
#if HELPER_TARGET_IS_ESP32 && ESP_IDF_VERSION < HELPER_ESP32_MIN_VER
#error Unsupported ESP-IDF version. Please update!
#endif
#if HELPER_TARGET_IS_ESP8266 && ESP_IDF_VERSION < HELPER_ESP8266_MIN_VER
#error Unsupported ESP8266 RTOS SDK version. Please update!
#endif
/* show the actual values for debugging */
#if DEBUG
#define VALUE_TO_STRING(x) #x
#define VALUE(x) VALUE_TO_STRING(x)
#define VAR_NAME_VALUE(var) #var "=" VALUE(var)
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP32C3))
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP32H2))
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP32S2))
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP32))
#pragma message(VAR_NAME_VALUE(CONFIG_IDF_TARGET_ESP8266))
#pragma message(VAR_NAME_VALUE(ESP_IDF_VERSION_MAJOR))
#endif
#endif

View File

@@ -0,0 +1,21 @@
#if CONFIG_IDF_TARGET_ESP32
#include <esp32/rom/ets_sys.h>
#elif CONFIG_IDF_TARGET_ESP32C2
#include <esp32c2/rom/ets_sys.h>
#elif CONFIG_IDF_TARGET_ESP32C3
#include <esp32c3/rom/ets_sys.h>
#elif CONFIG_IDF_TARGET_ESP32C6
#include <esp32c6/rom/ets_sys.h>
#elif CONFIG_IDF_TARGET_ESP32H2
#include <esp32h2/rom/ets_sys.h>
#elif CONFIG_IDF_TARGET_ESP32H4
#include <esp32h4/rom/ets_sys.h>
#elif CONFIG_IDF_TARGET_ESP32S2
#include <esp32s2/rom/ets_sys.h>
#elif CONFIG_IDF_TARGET_ESP32S3
#include <esp32s3/rom/ets_sys.h>
#elif CONFIG_IDF_TARGET_ESP8266
#include <rom/ets_sys.h>
#else
#error "ets_sys: Unknown target"
#endif

18
components/evse/CMakeLists.txt Executable file
View File

@@ -0,0 +1,18 @@
set(srcs
evse_core.c
evse_state.c
evse_error.c
evse_config.c
evse_limits.c
evse_events.c
evse_fsm.c
evse_manager.c
evse_hardware.c
)
idf_component_register(
SRCS ${srcs}
INCLUDE_DIRS "include"
PRIV_REQUIRES nvs_flash
REQUIRES peripherals
)

203
components/evse/evse_config.c Executable file
View File

@@ -0,0 +1,203 @@
#include "evse_config.h"
#include "board_config.h"
#include "evse_limits.h"
#include "esp_log.h"
#include "nvs.h"
static const char *TAG = "evse_config";
static nvs_handle_t nvs;
// Parâmetros configuráveis
static uint8_t max_charging_current = MAX_CHARGING_CURRENT_LIMIT;
static uint8_t grid_max_current = MAX_GRID_CURRENT_LIMIT;
static uint16_t charging_current;
static bool socket_outlet;
static bool rcm;
static uint8_t temp_threshold = 60;
static bool require_auth;
esp_err_t evse_config_init(void) {
ESP_LOGI(TAG, "Abrindo namespace NVS");
return nvs_open("evse", NVS_READWRITE, &nvs);
}
void evse_check_defaults(void) {
esp_err_t err;
uint8_t u8;
uint16_t u16;
uint32_t u32;
bool needs_commit = false;
// Max charging current
err = nvs_get_u8(nvs, "max_chrg_curr", &u8);
if (err != ESP_OK || u8 < MIN_CHARGING_CURRENT_LIMIT || u8 > MAX_CHARGING_CURRENT_LIMIT) {
max_charging_current = MAX_CHARGING_CURRENT_LIMIT;
nvs_set_u8(nvs, "max_chrg_curr", max_charging_current);
needs_commit = true;
} else {
max_charging_current = u8;
}
// Grid max current
err = nvs_get_u8(nvs, "grid_max_curr", &u8);
if (err != ESP_OK || u8 < MIN_GRID_CURRENT_LIMIT || u8 > MAX_GRID_CURRENT_LIMIT) {
grid_max_current = MAX_GRID_CURRENT_LIMIT;
nvs_set_u8(nvs, "grid_max_curr", grid_max_current);
needs_commit = true;
} else {
grid_max_current = u8;
}
// Charging current (decA)
err = nvs_get_u16(nvs, "def_chrg_curr", &u16);
if (err != ESP_OK || u16 < (MIN_CHARGING_CURRENT_LIMIT * 10) || u16 > (max_charging_current * 10)) {
charging_current = max_charging_current * 10;
nvs_set_u16(nvs, "def_chrg_curr", charging_current);
needs_commit = true;
} else {
charging_current = u16;
}
err = nvs_get_u8(nvs, "require_auth", &u8);
require_auth = (err == ESP_OK && u8 <= 1) ? u8 : false;
if (err != ESP_OK) {
nvs_set_u8(nvs, "require_auth", require_auth);
needs_commit = true;
}
err = nvs_get_u8(nvs, "socket_outlet", &u8);
socket_outlet = (err == ESP_OK && u8) && board_config.proximity;
if (err != ESP_OK) {
nvs_set_u8(nvs, "socket_outlet", socket_outlet);
needs_commit = true;
}
err = nvs_get_u8(nvs, "rcm", &u8);
rcm = (err == ESP_OK && u8) && board_config.rcm;
if (err != ESP_OK) {
nvs_set_u8(nvs, "rcm", rcm);
needs_commit = true;
}
err = nvs_get_u8(nvs, "temp_threshold", &u8);
temp_threshold = (err == ESP_OK && u8 >= 40 && u8 <= 80) ? u8 : 60;
if (err != ESP_OK) {
nvs_set_u8(nvs, "temp_threshold", temp_threshold);
needs_commit = true;
}
// Limites adicionais
if (nvs_get_u32(nvs, "def_cons_lim", &u32) == ESP_OK) {
evse_set_consumption_limit(u32);
}
if (nvs_get_u32(nvs, "def_ch_time_lim", &u32) == ESP_OK) {
evse_set_charging_time_limit(u32);
}
if (nvs_get_u16(nvs, "def_un_pwr_lim", &u16) == ESP_OK) {
evse_set_under_power_limit(u16);
}
if (needs_commit) {
nvs_commit(nvs);
}
}
// Corrente
uint8_t evse_get_max_charging_current(void) { return max_charging_current; }
esp_err_t evse_set_max_charging_current(uint8_t value) {
if (value < MIN_CHARGING_CURRENT_LIMIT || value > MAX_CHARGING_CURRENT_LIMIT)
return ESP_ERR_INVALID_ARG;
max_charging_current = value;
nvs_set_u8(nvs, "max_chrg_curr", value);
return nvs_commit(nvs);
}
uint8_t grid_get_max_current(void) { return grid_max_current; }
esp_err_t grid_set_max_current(uint8_t value) {
if (value < MIN_GRID_CURRENT_LIMIT || value > MAX_GRID_CURRENT_LIMIT)
return ESP_ERR_INVALID_ARG;
grid_max_current = value;
nvs_set_u8(nvs, "grid_max_curr", value);
return nvs_commit(nvs);
}
uint16_t evse_get_charging_current(void) { return charging_current; }
esp_err_t evse_set_charging_current(uint16_t value) {
if (value < (MIN_CHARGING_CURRENT_LIMIT * 10) || value > (max_charging_current * 10))
return ESP_ERR_INVALID_ARG;
charging_current = value;
nvs_set_u16(nvs, "def_chrg_curr", value);
return nvs_commit(nvs);
}
uint16_t evse_get_default_charging_current(void) {
uint16_t value;
nvs_get_u16(nvs, "def_chrg_curr", &value);
return value;
}
esp_err_t evse_set_default_charging_current(uint16_t value) {
if (value < (MIN_CHARGING_CURRENT_LIMIT * 10) || value > (max_charging_current * 10))
return ESP_ERR_INVALID_ARG;
nvs_set_u16(nvs, "def_chrg_curr", value);
return nvs_commit(nvs);
}
// Socket outlet
bool evse_get_socket_outlet(void) { return socket_outlet; }
esp_err_t evse_set_socket_outlet(bool value) {
if (value && !board_config.proximity) return ESP_ERR_INVALID_ARG;
socket_outlet = value;
nvs_set_u8(nvs, "socket_outlet", value);
return nvs_commit(nvs);
}
// RCM
bool evse_is_rcm(void) { return rcm; }
esp_err_t evse_set_rcm(bool value) {
if (value && !board_config.rcm) return ESP_ERR_INVALID_ARG;
rcm = value;
nvs_set_u8(nvs, "rcm", value);
return nvs_commit(nvs);
}
// Temperatura
uint8_t evse_get_temp_threshold(void) { return temp_threshold; }
esp_err_t evse_set_temp_threshold(uint8_t value) {
if (value < 40 || value > 80) return ESP_ERR_INVALID_ARG;
temp_threshold = value;
nvs_set_u8(nvs, "temp_threshold", value);
return nvs_commit(nvs);
}
// Autenticação
bool evse_is_require_auth(void) { return require_auth; }
void evse_set_require_auth(bool value) {
require_auth = value;
nvs_set_u8(nvs, "require_auth", value);
nvs_commit(nvs);
}
// Disponibilidade
static bool is_available = true;
bool evse_config_is_available(void) {
return is_available;
}
void evse_config_set_available(bool available) {
is_available = available;
}
// Ativação/desativação
static bool is_enabled = true;
bool evse_config_is_enabled(void) {
return is_enabled;
}
void evse_config_set_enabled(bool enabled) {
is_enabled = enabled;
}

131
components/evse/evse_core.c Executable file
View File

@@ -0,0 +1,131 @@
// evse_core.c - Função principal de controle do EVSE
#include "evse_fsm.h"
#include "evse_error.h"
#include "evse_limits.h"
#include "evse_config.h"
#include "evse_api.h"
#include "pilot.h"
#include "energy_meter.h"
#include "freertos/FreeRTOS.h"
#include "freertos/semphr.h"
#include "esp_log.h"
static const char *TAG = "evse_core";
static SemaphoreHandle_t mutex;
static evse_state_t last_state = EVSE_STATE_A;
static bool authorized = false;
static TickType_t auth_grant_to = 0;
static void evse_core_task(void *arg);
void evse_init(void) {
ESP_LOGI(TAG, "EVSE Init");
mutex = xSemaphoreCreateMutex();
evse_check_defaults();
evse_fsm_reset();
pilot_set_level(true); // Estado inicial do piloto
xTaskCreate(evse_core_task, "evse_core_task", 4096, NULL, 5, NULL);
}
void evse_process(void) {
xSemaphoreTake(mutex, portMAX_DELAY);
pilot_voltage_t pilot_voltage;
bool is_n12v = false;
pilot_measure(&pilot_voltage, &is_n12v);
ESP_LOGD(TAG, "Pilot: %d, -12V: %s", pilot_voltage, is_n12v ? "yes" : "no");
evse_error_check(pilot_voltage, is_n12v);
if (evse_get_error() == 0 && !evse_is_error_cleared()) {
// Autorização temporária se exigida
if (!authorized && evse_is_require_auth()) {
authorized = auth_grant_to >= xTaskGetTickCount();
if (auth_grant_to) auth_grant_to = 0;
} else {
authorized = true;
}
evse_fsm_process(
pilot_voltage,
authorized,
evse_config_is_available(),
evse_config_is_enabled()
);
evse_limits_check(evse_get_state());
evse_state_t current = evse_get_state();
if (current != last_state) {
ESP_LOGI(TAG, "State changed: %s → %s", evse_state_to_str(last_state), evse_state_to_str(current));
last_state = current;
}
}
if (evse_get_error() == 0) {
evse_mark_error_cleared();
}
xSemaphoreGive(mutex);
energy_meter_process(
evse_state_is_charging(evse_get_state()),
evse_get_charging_current()
);
}
// ================================
// Interface pública
// ================================
bool evse_is_enabled(void) {
return evse_config_is_enabled();
}
void evse_set_enabled(bool value) {
ESP_LOGI(TAG, "Set enabled %d", value);
evse_config_set_enabled(value);
}
bool evse_is_available(void) {
return evse_config_is_available();
}
void evse_set_available(bool value) {
ESP_LOGI(TAG, "Set available %d", value);
evse_config_set_available(value);
}
bool evse_is_pending_auth(void) {
return evse_state_is_session(evse_get_state()) && !authorized;
}
void evse_authorize(void) {
ESP_LOGI(TAG, "Authorize");
auth_grant_to = xTaskGetTickCount() + pdMS_TO_TICKS(60000);
}
void evse_set_authorized(bool value) {
ESP_LOGI(TAG, "Set authorized %d", value);
xSemaphoreTake(mutex, portMAX_DELAY);
authorized = value;
xSemaphoreGive(mutex);
}
// ================================
// Tarefa principal
// ================================
static void evse_core_task(void *arg) {
while (true) {
evse_process();
vTaskDelay(pdMS_TO_TICKS(100));
}
}

119
components/evse/evse_error.c Executable file
View File

@@ -0,0 +1,119 @@
#include "evse_error.h"
#include "evse_config.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "esp_log.h"
#include "ntc_sensor.h"
static const char *TAG = "evse_error";
static uint32_t error_bits = 0;
static TickType_t auto_clear_timeout = 0;
static bool error_cleared = false;
void evse_error_init(void) {
// Inicialização do sistema de erros
}
void evse_error_check(pilot_voltage_t pilot_voltage, bool is_n12v) {
ESP_LOGD(TAG, "Verificando erro: pilot_voltage = %d, is_n12v = %s",
pilot_voltage, is_n12v ? "true" : "false");
// Falha elétrica geral no pilot
if (pilot_voltage == PILOT_VOLTAGE_1) {
if (!(error_bits & EVSE_ERR_PILOT_FAULT_BIT)) { // Verifica se o erro já foi registrado
evse_error_set(EVSE_ERR_PILOT_FAULT_BIT);
ESP_LOGW(TAG, "Erro: pilot abaixo de 2V (falha)");
}
}
// Falta de -12V durante PWM (C ou D)
if ((pilot_voltage == PILOT_VOLTAGE_6 || pilot_voltage == PILOT_VOLTAGE_3) && !is_n12v) {
if (!(error_bits & EVSE_ERR_DIODE_SHORT_BIT)) { // Verifica se o erro já foi registrado
evse_error_set(EVSE_ERR_DIODE_SHORT_BIT);
ESP_LOGW(TAG, "Erro: ausência de -12V no PWM (sem diodo)");
}
}
}
void evse_temperature_check(void) {
float temp_c = ntc_temp_sensor(); // leitura atual (última medida válida)
uint8_t threshold = evse_get_temp_threshold(); // padrão 60°C, configurável
// Log informativo com os valores
ESP_LOGD(TAG, "Verificando temperatura: atual = %.2f °C, limite = %d °C", temp_c, threshold);
// Se a temperatura parecer inválida, aplica erro de sensor
if (temp_c < -40.0f || temp_c > 150.0f) {
if (!(error_bits & EVSE_ERR_TEMPERATURE_FAULT_BIT)) { // Verifica se o erro já foi registrado
evse_error_set(EVSE_ERR_TEMPERATURE_FAULT_BIT);
ESP_LOGW(TAG, "Sensor NTC falhou ou está desconectado");
}
return;
}
evse_error_clear(EVSE_ERR_TEMPERATURE_FAULT_BIT); // leitura válida
if (temp_c >= threshold) {
if (!(error_bits & EVSE_ERR_TEMPERATURE_HIGH_BIT)) { // Verifica se o erro já foi registrado
evse_error_set(EVSE_ERR_TEMPERATURE_HIGH_BIT);
ESP_LOGW(TAG, "Temperatura acima do limite: %.2f °C ≥ %d °C", temp_c, threshold);
}
} else {
evse_error_clear(EVSE_ERR_TEMPERATURE_HIGH_BIT);
}
}
uint32_t evse_get_error(void) {
return error_bits;
}
bool evse_is_error_cleared(void) {
return error_cleared;
}
void evse_mark_error_cleared(void) {
error_cleared = false;
}
// Já existentes
void evse_error_set(uint32_t bitmask) {
error_bits |= bitmask;
if (bitmask & EVSE_ERR_AUTO_CLEAR_BITS) {
auto_clear_timeout = xTaskGetTickCount() + pdMS_TO_TICKS(60000); // 60s
}
}
void evse_error_clear(uint32_t bitmask) {
bool had_error = error_bits != 0;
error_bits &= ~bitmask;
if (had_error && error_bits == 0) {
error_cleared = true;
}
}
void evse_error_tick(void) {
if ((error_bits & EVSE_ERR_AUTO_CLEAR_BITS) && xTaskGetTickCount() >= auto_clear_timeout) {
evse_error_clear(EVSE_ERR_AUTO_CLEAR_BITS);
auto_clear_timeout = 0;
}
}
bool evse_error_is_active(void) {
return error_bits != 0;
}
uint32_t evse_error_get_bits(void) {
return error_bits;
}
void evse_error_reset_flag(void) {
error_cleared = false;
}
bool evse_error_cleared_flag(void) {
return error_cleared;
}

3
components/evse/evse_events.c Executable file
View File

@@ -0,0 +1,3 @@
#include "evse_events.h"
ESP_EVENT_DEFINE_BASE(EVSE_EVENT);

175
components/evse/evse_fsm.c Executable file
View File

@@ -0,0 +1,175 @@
// evse_fsm.c - Máquina de Estados EVSE com controle centralizado
#include "evse_fsm.h"
#include "evse_api.h"
#include "pilot.h"
#include "esp_log.h"
#include "ac_relay.h"
#include "board_config.h"
#include "socket_lock.h"
#include "energy_meter.h"
#include "proximity.h"
#include "rcm.h"
#include "evse_state.h"
static const char *TAG = "evse_fsm";
#ifndef MIN
#define MIN(a, b) ((a) < (b) ? (a) : (b))
#endif
static bool c1_d1_waiting = false;
static TickType_t c1_d1_relay_to = 0;
void evse_fsm_reset(void) {
evse_set_state(EVSE_STATE_A);
c1_d1_waiting = false;
c1_d1_relay_to = 0;
}
static void update_outputs(evse_state_t state, uint16_t charging_current, uint8_t cable_max_current, bool socket_outlet) {
switch (state) {
case EVSE_STATE_A:
case EVSE_STATE_E:
case EVSE_STATE_F:
ac_relay_set_state(false);
pilot_set_level(state == EVSE_STATE_A);
if (board_config.socket_lock && socket_outlet) {
socket_lock_set_locked(false);
}
energy_meter_stop_session();
break;
case EVSE_STATE_B1:
pilot_set_level(true);
ac_relay_set_state(false);
if (board_config.socket_lock && socket_outlet) {
socket_lock_set_locked(true);
}
if (rcm_test()) {
ESP_LOGI(TAG, "RCM self test passed");
} else {
ESP_LOGW(TAG, "RCM self test failed");
}
if (socket_outlet) {
cable_max_current = proximity_get_max_current();
}
energy_meter_start_session();
break;
case EVSE_STATE_B2:
pilot_set_amps(MIN(charging_current, cable_max_current * 10));
ac_relay_set_state(false);
break;
case EVSE_STATE_C1:
case EVSE_STATE_D1:
pilot_set_level(true);
c1_d1_waiting = true;
c1_d1_relay_to = xTaskGetTickCount() + pdMS_TO_TICKS(6000);
break;
case EVSE_STATE_C2:
case EVSE_STATE_D2:
pilot_set_amps(MIN(charging_current, cable_max_current * 10));
ac_relay_set_state(true);
break;
}
}
void evse_fsm_process(pilot_voltage_t pilot_voltage, bool authorized, bool available, bool enabled) {
TickType_t now = xTaskGetTickCount();
evse_state_t previous_state = evse_get_state();
evse_state_t current_state = previous_state;
switch (current_state) {
case EVSE_STATE_A:
if (!available) {
evse_set_state(EVSE_STATE_F);
} else if (pilot_voltage == PILOT_VOLTAGE_9) {
evse_set_state(EVSE_STATE_B1);
}
break;
case EVSE_STATE_B1:
case EVSE_STATE_B2:
if (!available) {
evse_set_state(EVSE_STATE_F);
break;
}
switch (pilot_voltage) {
case PILOT_VOLTAGE_12:
evse_set_state(EVSE_STATE_A);
break;
case PILOT_VOLTAGE_9:
evse_set_state((authorized && enabled) ? EVSE_STATE_B2 : EVSE_STATE_B1);
break;
case PILOT_VOLTAGE_6:
evse_set_state((authorized && enabled) ? EVSE_STATE_C2 : EVSE_STATE_C1);
break;
default:
break;
}
break;
case EVSE_STATE_C1:
case EVSE_STATE_D1:
if (c1_d1_waiting && now >= c1_d1_relay_to) {
ac_relay_set_state(false);
c1_d1_waiting = false;
if (!available) {
evse_set_state(EVSE_STATE_F);
break;
}
}
// fallthrough intencional
case EVSE_STATE_C2:
case EVSE_STATE_D2:
if (!enabled || !available) {
evse_set_state(
(current_state == EVSE_STATE_D2 || current_state == EVSE_STATE_D1)
? EVSE_STATE_D1
: EVSE_STATE_C1
);
break;
}
switch (pilot_voltage) {
case PILOT_VOLTAGE_6:
evse_set_state((authorized && enabled) ? EVSE_STATE_C2 : EVSE_STATE_C1);
break;
case PILOT_VOLTAGE_3:
evse_set_state((authorized && enabled) ? EVSE_STATE_D2 : EVSE_STATE_D1);
break;
case PILOT_VOLTAGE_9:
evse_set_state((authorized && enabled) ? EVSE_STATE_B2 : EVSE_STATE_B1);
break;
case PILOT_VOLTAGE_12:
evse_set_state(EVSE_STATE_A);
break;
default:
break;
}
break;
case EVSE_STATE_E:
// Sem transições a partir de E
break;
case EVSE_STATE_F:
if (available) {
evse_set_state(EVSE_STATE_A);
}
break;
}
evse_state_t new_state = evse_get_state();
if (new_state != previous_state) {
ESP_LOGI(TAG, "State changed: %s -> %s", evse_state_to_str(previous_state), evse_state_to_str(new_state));
update_outputs(new_state, evse_get_charging_current(), evse_get_max_charging_current(), evse_get_socket_outlet());
}
}

View File

@@ -0,0 +1,55 @@
#include "evse_hardware.h"
#include "pilot.h"
#include "ac_relay.h"
#include "socket_lock.h"
#include "proximity.h"
static const char *TAG = "evse_hardware";
void evse_hardware_init(void) {
pilot_set_level(true); // Sinal piloto em 12V (inicial)
ac_relay_set_state(false); // Relé desligado
//socket_lock_set_locked(false); // Destrava o conector
}
void evse_hardware_tick(void) {
// Tick para atualizações de hardware com polling, se necessário
}
bool evse_hardware_is_pilot_high(void) {
return pilot_get_state(); // true se sinal piloto estiver em nível alto
}
bool evse_hardware_is_vehicle_connected(void) {
// Verifica se o veículo está conectado pelo resistor do pino PP
return proximity_get_max_current() > 0;
}
bool evse_hardware_is_energy_detected(void) {
// TODO: Substituir com medição real de corrente ou consumo
return true;
}
void evse_hardware_relay_on(void) {
ac_relay_set_state(true);
}
void evse_hardware_relay_off(void) {
ac_relay_set_state(false);
}
bool evse_hardware_relay_status(void) {
return ac_relay_get_state();
}
void evse_hardware_lock(void) {
socket_lock_set_locked(true);
}
void evse_hardware_unlock(void) {
socket_lock_set_locked(false);
}
bool evse_hardware_is_locked(void) {
return socket_lock_get_status() == SOCKED_LOCK_STATUS_IDLE;
}

97
components/evse/evse_limits.c Executable file
View File

@@ -0,0 +1,97 @@
#include "evse_limits.h"
#include <stdint.h>
#include <stdbool.h>
// ========================
// Estado interno
// ========================
static bool limit_reached = false;
static uint32_t consumption_limit = 0;
static uint32_t charging_time_limit = 0;
static uint16_t under_power_limit = 0;
static uint32_t default_consumption_limit = 0;
static uint32_t default_charging_time_limit = 0;
static uint16_t default_under_power_limit = 0;
// ========================
// Estado de controle
// ========================
void evse_set_limit_reached(uint8_t value) {
limit_reached = (value != 0);
}
bool evse_is_limit_reached(void) {
return limit_reached;
}
// ========================
// Limites em tempo de execução
// ========================
uint32_t evse_get_consumption_limit(void) {
return consumption_limit;
}
void evse_set_consumption_limit(uint32_t value) {
consumption_limit = value;
}
uint32_t evse_get_charging_time_limit(void) {
return charging_time_limit;
}
void evse_set_charging_time_limit(uint32_t value) {
charging_time_limit = value;
}
uint16_t evse_get_under_power_limit(void) {
return under_power_limit;
}
void evse_set_under_power_limit(uint16_t value) {
under_power_limit = value;
}
// ========================
// Limites padrão (persistentes)
// ========================
uint32_t evse_get_default_consumption_limit(void) {
return default_consumption_limit;
}
void evse_set_default_consumption_limit(uint32_t value) {
default_consumption_limit = value;
}
uint32_t evse_get_default_charging_time_limit(void) {
return default_charging_time_limit;
}
void evse_set_default_charging_time_limit(uint32_t value) {
default_charging_time_limit = value;
}
uint16_t evse_get_default_under_power_limit(void) {
return default_under_power_limit;
}
void evse_set_default_under_power_limit(uint16_t value) {
default_under_power_limit = value;
}
// ========================
// Lógica de verificação de limites
// ========================
void evse_limits_check(evse_state_t state) {
// Se algum limite estiver ativo, verifique o estado
if ((consumption_limit > 0 || charging_time_limit > 0 || under_power_limit > 0)
&& evse_state_is_charging(state)) {
// (Lógica real a ser aplicada aqui, ex: medição de consumo, tempo ou potência)
evse_set_limit_reached(1);
}
}

View File

@@ -0,0 +1,81 @@
#include "evse_manager.h"
#include "evse_state.h"
#include "evse_error.h"
#include "evse_hardware.h"
#include "evse_config.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "esp_log.h"
static const char *TAG = "evse_manager";
static SemaphoreHandle_t evse_mutex;
#define EVSE_MANAGER_TICK_PERIOD_MS 1000 // 1 segundo
void evse_manager_init(void) {
evse_mutex = xSemaphoreCreateMutex();
evse_config_init();
evse_error_init();
evse_hardware_init();
evse_state_init();
ESP_LOGI(TAG, "EVSE Manager initialized");
xTaskCreate(
evse_manager_task,
"evse_manager_task",
4096, // stack size
NULL, // param
5, // priority
NULL // handle
);
}
void evse_manager_task(void *arg) {
while (true) {
evse_manager_tick();
vTaskDelay(pdMS_TO_TICKS(EVSE_MANAGER_TICK_PERIOD_MS));
}
}
void evse_manager_tick(void) {
xSemaphoreTake(evse_mutex, portMAX_DELAY);
// Atualizações cíclicas de módulos
evse_hardware_tick();
evse_error_tick();
evse_state_tick();
evse_temperature_check();
xSemaphoreGive(evse_mutex);
}
bool evse_manager_is_available(void) {
return evse_config_is_available();
}
void evse_manager_set_available(bool available) {
evse_config_set_available(available);
}
void evse_manager_set_authorized(bool authorized) {
evse_state_set_authorized(authorized);
}
bool evse_manager_is_charging(void) {
return evse_state_is_charging(evse_get_state());
}
void evse_manager_set_enabled(bool enabled) {
evse_config_set_enabled(enabled);
}
bool evse_manager_is_enabled(void) {
return evse_config_is_enabled();
}

View File

@@ -0,0 +1,49 @@
#include "evse_state.h"
static evse_state_t current_state = EVSE_STATE_A;
void evse_set_state(evse_state_t state) {
current_state = state;
}
evse_state_t evse_get_state(void) {
return current_state;
}
const char* evse_state_to_str(evse_state_t state) {
switch (state) {
case EVSE_STATE_A: return "A - EV Not Connected (12V)";
case EVSE_STATE_B1: return "B1 - EV Connected (9V, Not Authorized)";
case EVSE_STATE_B2: return "B2 - EV Connected (9V, Authorized and Ready)";
case EVSE_STATE_C1: return "C1 - Charging Requested (6V, Relay Off)";
case EVSE_STATE_C2: return "C2 - Charging Active (6V, Relay On)";
case EVSE_STATE_D1: return "D1 - Ventilation Required (3V, Relay Off)";
case EVSE_STATE_D2: return "D2 - Ventilation Active (3V, Relay On)";
case EVSE_STATE_E: return "E - Error: Control Pilot Shorted to Ground (0V)";
case EVSE_STATE_F: return "F - Fault: EVSE Unavailable or No Pilot Signal";
default: return "Unknown State";
}
}
void evse_state_init(void) {
// Inicialização do estado EVSE
}
void evse_state_tick(void) {
// Tick do estado (placeholder)
}
bool evse_state_is_charging(evse_state_t state) {
return state == EVSE_STATE_C1 || state == EVSE_STATE_C2;
}
bool evse_state_is_plugged(evse_state_t state) {
return state == EVSE_STATE_B1 || state == EVSE_STATE_B2 ||
state == EVSE_STATE_C1 || state == EVSE_STATE_C2 ||
state == EVSE_STATE_D1 || state == EVSE_STATE_D2;
}
bool evse_state_is_session(evse_state_t state) {
return state == EVSE_STATE_B2 || state == EVSE_STATE_C1 || state == EVSE_STATE_C2;
}

View File

@@ -0,0 +1,70 @@
#ifndef EVSE_API_H
#define EVSE_API_H
#include <stdint.h>
#include <stdbool.h>
#include "esp_err.h"
#include "evse_state.h" // Define evse_state_t
// Inicialização
void evse_init(void);
void evse_process(void);
// Estado
evse_state_t evse_get_state(void);
const char* evse_state_to_str(evse_state_t state);
bool evse_is_connector_plugged(evse_state_t state);
bool evse_is_limit_reached(void);
// Autorização e disponibilidade
bool evse_is_enabled(void);
void evse_set_enabled(bool value);
bool evse_is_available(void);
void evse_set_available(bool value);
bool evse_is_require_auth(void);
void evse_set_require_auth(bool value);
void evse_authorize(void);
bool evse_is_pending_auth(void);
void evse_set_authorized(bool value);
// Corrente
uint16_t evse_get_charging_current(void);
esp_err_t evse_set_charging_current(uint16_t value);
uint16_t evse_get_default_charging_current(void);
esp_err_t evse_set_default_charging_current(uint16_t value);
uint8_t evse_get_max_charging_current(void);
esp_err_t evse_set_max_charging_current(uint8_t value);
// Grid
uint8_t grid_get_max_current(void);
esp_err_t grid_set_max_current(uint8_t value);
// Temperatura
uint8_t evse_get_temp_threshold(void);
esp_err_t evse_set_temp_threshold(uint8_t value);
// RCM / Socket
bool evse_get_socket_outlet(void);
esp_err_t evse_set_socket_outlet(bool value);
bool evse_is_rcm(void);
esp_err_t evse_set_rcm(bool value);
// Limites
uint32_t evse_get_consumption_limit(void);
void evse_set_consumption_limit(uint32_t value);
uint32_t evse_get_charging_time_limit(void);
void evse_set_charging_time_limit(uint32_t value);
uint16_t evse_get_under_power_limit(void);
void evse_set_under_power_limit(uint16_t value);
void evse_set_limit_reached(uint8_t value);
// Limites default
uint32_t evse_get_default_consumption_limit(void);
void evse_set_default_consumption_limit(uint32_t value);
uint32_t evse_get_default_charging_time_limit(void);
void evse_set_default_charging_time_limit(uint32_t value);
uint16_t evse_get_default_under_power_limit(void);
void evse_set_default_under_power_limit(uint16_t value);
#endif // EVSE_API_H

View File

@@ -0,0 +1,78 @@
#ifndef EVSE_CONFIG_H
#define EVSE_CONFIG_H
#include <stdbool.h>
#include <stdint.h>
#include "esp_err.h"
#ifdef __cplusplus
extern "C" {
#endif
// ========================
// Limites Globais (Defines)
// ========================
// Corrente máxima de carregamento (configurável pelo usuário)
#define MIN_CHARGING_CURRENT_LIMIT 6 // A
#define MAX_CHARGING_CURRENT_LIMIT 16 // A
// Corrente máxima da rede elétrica (grid)
#define MIN_GRID_CURRENT_LIMIT 6 // A
#define MAX_GRID_CURRENT_LIMIT 100 // A
// Corrente via cabo (proximity) — se configurável
#define MIN_CABLE_CURRENT_LIMIT 6 // A
#define MAX_CABLE_CURRENT_LIMIT 63 // A
// ========================
// Funções de Configuração
// ========================
// Inicialização
esp_err_t evse_config_init(void);
void evse_check_defaults(void);
// Corrente de carregamento
uint8_t evse_get_max_charging_current(void);
esp_err_t evse_set_max_charging_current(uint8_t value);
uint16_t evse_get_charging_current(void);
esp_err_t evse_set_charging_current(uint16_t value);
uint16_t evse_get_default_charging_current(void);
esp_err_t evse_set_default_charging_current(uint16_t value);
// Corrente da rede elétrica
uint8_t grid_get_max_current(void);
esp_err_t grid_set_max_current(uint8_t value);
// Configuração de socket outlet
bool evse_get_socket_outlet(void);
esp_err_t evse_set_socket_outlet(bool socket_outlet);
// RCM
bool evse_is_rcm(void);
esp_err_t evse_set_rcm(bool rcm);
// Temperatura
uint8_t evse_get_temp_threshold(void);
esp_err_t evse_set_temp_threshold(uint8_t threshold);
// Autenticação
bool evse_is_require_auth(void);
void evse_set_require_auth(bool require);
// Disponibilidade
bool evse_config_is_available(void);
void evse_config_set_available(bool available);
// Ativação/desativação do EVSE
bool evse_config_is_enabled(void);
void evse_config_set_enabled(bool enabled);
#ifdef __cplusplus
}
#endif
#endif // EVSE_CONFIG_H

View File

@@ -0,0 +1,45 @@
#ifndef EVSE_ERROR_H
#define EVSE_ERROR_H
#include <stdint.h>
#include <stdbool.h>
#include "pilot.h"
#define EVSE_ERR_AUTO_CLEAR_BITS ( \
EVSE_ERR_DIODE_SHORT_BIT | \
EVSE_ERR_TEMPERATURE_HIGH_BIT | \
EVSE_ERR_RCM_TRIGGERED_BIT )
// Error bits
#define EVSE_ERR_DIODE_SHORT_BIT (1 << 0)
#define EVSE_ERR_LOCK_FAULT_BIT (1 << 1)
#define EVSE_ERR_UNLOCK_FAULT_BIT (1 << 2)
#define EVSE_ERR_RCM_SELFTEST_FAULT_BIT (1 << 3)
#define EVSE_ERR_RCM_TRIGGERED_BIT (1 << 4)
#define EVSE_ERR_TEMPERATURE_HIGH_BIT (1 << 5)
#define EVSE_ERR_PILOT_FAULT_BIT (1 << 6)
#define EVSE_ERR_TEMPERATURE_FAULT_BIT (1 << 7)
// Inicialização do módulo de erros
void evse_error_init(void);
// Verificações e monitoramento
void evse_error_check(pilot_voltage_t pilot_voltage, bool is_n12v);
void evse_temperature_check(void);
void evse_error_tick(void);
// Leitura e controle de erros
uint32_t evse_get_error(void);
bool evse_is_error_cleared(void);
void evse_mark_error_cleared(void);
void evse_error_set(uint32_t bitmask);
void evse_error_clear(uint32_t bitmask);
bool evse_error_is_active(void);
uint32_t evse_error_get_bits(void);
void evse_error_reset_flag(void);
bool evse_error_cleared_flag(void);
#endif // EVSE_ERROR_H

View File

@@ -0,0 +1,33 @@
#ifndef EVSE_EVENTS_H
#define EVSE_EVENTS_H
#include "evse_api.h"
#include "esp_event_base.h"
// Certifique-se de que ESP_EVENT_DECLARE_BASE seja corretamente reconhecido
#ifdef __cplusplus
extern "C" {
#endif
// Declaração da base de eventos EVSE (será definida em evse_events.c)
ESP_EVENT_DECLARE_BASE(EVSE_EVENT);
typedef enum {
EVSE_EVENT_STATE_CHANGED,
EVSE_EVENT_ERROR,
EVSE_EVENT_ERROR_CLEARED,
EVSE_EVENT_LIMIT_REACHED,
EVSE_EVENT_AUTH_GRANTED
} evse_event_id_t;
// Estrutura do evento de mudança de estado
typedef struct {
evse_state_t previous;
evse_state_t current;
} evse_event_state_changed_t;
#ifdef __cplusplus
}
#endif
#endif // EVSE_EVENTS_H

View File

@@ -0,0 +1,37 @@
#ifndef EVSE_FSM_H
#define EVSE_FSM_H
#include <stdint.h>
#include <stdbool.h>
#include "evse_api.h"
#include "pilot.h"
#include "freertos/FreeRTOS.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* @brief Reinicia a máquina de estados do EVSE para o estado inicial (A).
*/
void evse_fsm_reset(void);
/**
* @brief Processa uma leitura do sinal de piloto e atualiza a máquina de estados do EVSE.
*
* Esta função deve ser chamada periodicamente pelo núcleo de controle para
* avaliar mudanças no estado do conector, disponibilidade do carregador e
* autorização do usuário.
*
* @param pilot_voltage Leitura atual da tensão do sinal piloto.
* @param authorized Indica se o carregamento foi autorizado.
* @param available Indica se o carregador está disponível (ex: sem falhas).
* @param enabled Indica se o carregador está habilitado via software.
*/
void evse_fsm_process(pilot_voltage_t pilot_voltage, bool authorized, bool available, bool enabled);
#ifdef __cplusplus
}
#endif
#endif // EVSE_FSM_H

View File

@@ -0,0 +1,71 @@
#ifndef EVSE_HARDWARE_H
#define EVSE_HARDWARE_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
/**
* @brief Inicializa todos os periféricos de hardware do EVSE (pilot, relé, trava, etc.)
*/
void evse_hardware_init(void);
/**
* @brief Executa atualizações periódicas no hardware (tick)
*/
void evse_hardware_tick(void);
/**
* @brief Verifica se o sinal piloto está em nível alto (12V)
*/
bool evse_hardware_is_pilot_high(void);
/**
* @brief Verifica se o veículo está fisicamente conectado via Proximity
*/
bool evse_hardware_is_vehicle_connected(void);
/**
* @brief Verifica se há consumo de energia (corrente detectada)
*/
bool evse_hardware_is_energy_detected(void);
/**
* @brief Liga o relé de fornecimento de energia
*/
void evse_hardware_relay_on(void);
/**
* @brief Desliga o relé de fornecimento de energia
*/
void evse_hardware_relay_off(void);
/**
* @brief Consulta o estado atual do relé
* @return true se ligado, false se desligado
*/
bool evse_hardware_relay_status(void);
/**
* @brief Aciona a trava física do conector
*/
void evse_hardware_lock(void);
/**
* @brief Libera a trava física do conector
*/
void evse_hardware_unlock(void);
/**
* @brief Verifica se o conector está travado
*/
bool evse_hardware_is_locked(void);
#ifdef __cplusplus
}
#endif
#endif // EVSE_HARDWARE_H

View File

@@ -0,0 +1,43 @@
#ifndef EVSE_LIMITS_H
#define EVSE_LIMITS_H
#include <stdint.h>
#include <stdbool.h>
#include "evse_state.h"
#ifdef __cplusplus
extern "C" {
#endif
/// Estado dos limites
void evse_set_limit_reached(uint8_t value);
bool evse_is_limit_reached(void);
/// Verifica e aplica lógica de limites com base no estado atual do EVSE
void evse_limits_check(evse_state_t state);
/// Limites ativos (runtime)
uint32_t evse_get_consumption_limit(void);
void evse_set_consumption_limit(uint32_t value);
uint32_t evse_get_charging_time_limit(void);
void evse_set_charging_time_limit(uint32_t value);
uint16_t evse_get_under_power_limit(void);
void evse_set_under_power_limit(uint16_t value);
/// Limites padrão (persistentes)
uint32_t evse_get_default_consumption_limit(void);
void evse_set_default_consumption_limit(uint32_t value);
uint32_t evse_get_default_charging_time_limit(void);
void evse_set_default_charging_time_limit(uint32_t value);
uint16_t evse_get_default_under_power_limit(void);
void evse_set_default_under_power_limit(uint16_t value);
#ifdef __cplusplus
}
#endif
#endif // EVSE_LIMITS_H

View File

@@ -0,0 +1,63 @@
#ifndef EVSE_MANAGER_H
#define EVSE_MANAGER_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include "evse_state.h"
#include "evse_error.h"
#include "evse_config.h"
/**
* @brief Inicializa todos os módulos do EVSE e inicia a tarefa de supervisão periódica.
*/
void evse_manager_init(void);
/**
* @brief Executa uma iteração do ciclo de controle do EVSE (chamada automaticamente pela task).
*
* Você normalmente não precisa chamar isso manualmente.
*/
void evse_manager_tick(void);
/**
* @brief Verifica se o EVSE está disponível para conexão (não bloqueado, sem falha crítica, etc).
*/
bool evse_manager_is_available(void);
/**
* @brief Define se o EVSE deve estar disponível.
*
* Pode ser usado, por exemplo, para bloquear carregamento via comando remoto.
*/
void evse_manager_set_available(bool available);
/**
* @brief Define se o EVSE está autorizado a iniciar carregamento (ex: após autenticação).
*/
void evse_manager_set_authorized(bool authorized);
/**
* @brief Verifica se o EVSE está em estado de carregamento ativo.
*/
bool evse_manager_is_charging(void);
/**
* @brief Ativa ou desativa o EVSE (liga/desliga logicamente o carregamento).
*/
void evse_manager_set_enabled(bool enabled);
/**
* @brief Verifica se o EVSE está ativado logicamente.
*/
bool evse_manager_is_enabled(void);
void evse_manager_task(void *arg);
#ifdef __cplusplus
}
#endif
#endif // EVSE_MANAGER_H

View File

@@ -0,0 +1,42 @@
#ifndef EVSE_STATE_H
#define EVSE_STATE_H
#include <stdbool.h>
// Estado do EVSE (pilot signal)
typedef enum {
EVSE_STATE_A,
EVSE_STATE_B1,
EVSE_STATE_B2,
EVSE_STATE_C1,
EVSE_STATE_C2,
EVSE_STATE_D1,
EVSE_STATE_D2,
EVSE_STATE_E,
EVSE_STATE_F
} evse_state_t;
// Funções públicas necessárias
void evse_state_init(void);
void evse_state_tick(void);
void evse_state_set_authorized(bool authorized);
evse_state_t evse_get_state(void);
void evse_set_state(evse_state_t state);
// Converte o estado para string
const char* evse_state_to_str(evse_state_t state);
// Retorna true se o estado representa sessão ativa
bool evse_state_is_session(evse_state_t state);
// Retorna true se o estado representa carregamento ativo
bool evse_state_is_charging(evse_state_t state);
// Retorna true se o estado representa veículo conectado
bool evse_state_is_plugged(evse_state_t state);
#endif // EVSE_STATE_H

View File

@@ -0,0 +1,3 @@
idf_component_register(SRCS "button/button.c" "button/button_obj.cpp"
INCLUDE_DIRS "button/include"
REQUIRES "driver")

6
components/gpio_button/Kconfig Executable file
View File

@@ -0,0 +1,6 @@
menu "GPIO Button"
config IO_GLITCH_FILTER_TIME_MS
int "IO glitch filter timer ms (10~100)"
range 10 100
default 50
endmenu

View File

@@ -0,0 +1,353 @@
// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <stdio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <freertos/queue.h>
#include <freertos/timers.h>
#include <esp_log.h>
#include <driver/gpio.h>
#include <iot_button.h>
#define IOT_CHECK(tag, a, ret) if(!(a)) { \
ESP_LOGE(tag,"%s:%d (%s)", __FILE__, __LINE__, __FUNCTION__); \
return (ret); \
}
#define ERR_ASSERT(tag, param) IOT_CHECK(tag, (param) == ESP_OK, ESP_FAIL)
#define POINT_ASSERT(tag, param, ret) IOT_CHECK(tag, (param) != NULL, (ret))
typedef enum {
BUTTON_STATE_IDLE = 0,
BUTTON_STATE_PUSH,
BUTTON_STATE_PRESSED,
} button_status_t;
typedef struct button_dev button_dev_t;
typedef struct btn_cb button_cb_t;
struct btn_cb{
TickType_t interval;
button_cb cb;
void* arg;
uint8_t on_press;
TimerHandle_t tmr;
button_dev_t *pbtn;
button_cb_t *next_cb;
};
struct button_dev{
uint8_t io_num;
uint8_t active_level;
uint32_t serial_thres_sec;
uint8_t taskq_on;
QueueHandle_t taskq;
QueueHandle_t argq;
button_status_t state;
button_cb_t tap_short_cb;
button_cb_t tap_psh_cb;
button_cb_t tap_rls_cb;
button_cb_t press_serial_cb;
button_cb_t* cb_head;
};
#define BUTTON_GLITCH_FILTER_TIME_MS CONFIG_IO_GLITCH_FILTER_TIME_MS
static const char* TAG = "button";
static void button_press_cb(TimerHandle_t tmr)
{
button_cb_t* btn_cb = (button_cb_t*) pvTimerGetTimerID(tmr);
button_dev_t* btn = btn_cb->pbtn;
// low, then restart
if (btn->active_level == gpio_get_level(btn->io_num)) {
btn->state = BUTTON_STATE_PRESSED;
if (btn->taskq != NULL && btn->argq != NULL && btn->taskq_on && !btn_cb->on_press) {
void *tmp = btn_cb->cb;
xQueueOverwrite(btn->taskq, &tmp);
xQueueOverwrite(btn->argq, &btn_cb->arg);
} else if (btn_cb->cb) {
btn_cb->cb(btn_cb->arg);
}
}
}
static void button_tap_psh_cb(TimerHandle_t tmr)
{
button_cb_t* btn_cb = (button_cb_t*) pvTimerGetTimerID(tmr);
button_dev_t* btn = btn_cb->pbtn;
xTimerStop(btn->tap_rls_cb.tmr, portMAX_DELAY);
int lv = gpio_get_level(btn->io_num);
if (btn->active_level == lv) {
// True implies key is pressed
btn->state = BUTTON_STATE_PUSH;
if (btn->press_serial_cb.tmr) {
xTimerChangePeriod(btn->press_serial_cb.tmr, btn->serial_thres_sec*1000 / portTICK_PERIOD_MS, portMAX_DELAY);
xTimerReset(btn->press_serial_cb.tmr, portMAX_DELAY);
}
if (btn->tap_psh_cb.cb) {
btn->tap_psh_cb.cb(btn->tap_psh_cb.arg);
}
} else {
// 50ms, check if this is a real key up
if (btn->tap_rls_cb.tmr) {
xTimerStop(btn->tap_rls_cb.tmr, portMAX_DELAY);
xTimerReset(btn->tap_rls_cb.tmr, portMAX_DELAY);
}
}
}
static void button_tap_rls_cb(TimerHandle_t tmr)
{
button_cb_t* btn_cb = (button_cb_t*) pvTimerGetTimerID(tmr);
button_dev_t* btn = btn_cb->pbtn;
xTimerStop(btn->tap_rls_cb.tmr, portMAX_DELAY);
if (btn->active_level == gpio_get_level(btn->io_num)) {
} else {
// high, then key is up
button_cb_t *pcb = btn->cb_head;
while (pcb != NULL) {
if (pcb->tmr != NULL) {
xTimerStop(pcb->tmr, portMAX_DELAY);
}
pcb = pcb->next_cb;
}
if (btn->taskq != NULL && btn->argq != NULL && btn->taskq_on && uxQueueMessagesWaiting(btn->taskq) != 0 && btn->state != BUTTON_STATE_IDLE) {
void (*task)(void*);
void *arg;
xQueueReceive(btn->taskq, &task, 0);
xQueueReceive(btn->argq, &arg, 0);
task(arg);
}
if (btn->press_serial_cb.tmr && btn->press_serial_cb.tmr != NULL) {
xTimerStop(btn->press_serial_cb.tmr, portMAX_DELAY);
}
if (btn->tap_short_cb.cb && btn->state == BUTTON_STATE_PUSH) {
btn->tap_short_cb.cb(btn->tap_short_cb.arg);
}
if(btn->tap_rls_cb.cb && btn->state != BUTTON_STATE_IDLE) {
btn->tap_rls_cb.cb(btn->tap_rls_cb.arg);
}
btn->state = BUTTON_STATE_IDLE;
}
}
static void button_press_serial_cb(TimerHandle_t tmr)
{
button_dev_t* btn = (button_dev_t*) pvTimerGetTimerID(tmr);
if (btn->press_serial_cb.cb) {
btn->press_serial_cb.cb(btn->press_serial_cb.arg);
}
xTimerChangePeriod(btn->press_serial_cb.tmr, btn->press_serial_cb.interval, portMAX_DELAY);
xTimerReset(btn->press_serial_cb.tmr, portMAX_DELAY);
}
static void button_gpio_isr_handler(void* arg)
{
button_dev_t* btn = (button_dev_t*) arg;
portBASE_TYPE HPTaskAwoken = pdFALSE;
int level = gpio_get_level(btn->io_num);
if (level == btn->active_level) {
if (btn->tap_psh_cb.tmr) {
xTimerStopFromISR(btn->tap_psh_cb.tmr, &HPTaskAwoken);
xTimerResetFromISR(btn->tap_psh_cb.tmr, &HPTaskAwoken);
}
button_cb_t *pcb = btn->cb_head;
while (pcb != NULL) {
if (pcb->tmr != NULL) {
xTimerStopFromISR(pcb->tmr, &HPTaskAwoken);
xTimerResetFromISR(pcb->tmr, &HPTaskAwoken);
}
pcb = pcb->next_cb;
}
} else {
// 50ms, check if this is a real key up
if (btn->tap_rls_cb.tmr) {
xTimerStopFromISR(btn->tap_rls_cb.tmr, &HPTaskAwoken);
xTimerResetFromISR(btn->tap_rls_cb.tmr, &HPTaskAwoken);
}
}
if(HPTaskAwoken == pdTRUE) {
portYIELD_FROM_ISR();
}
}
static void button_free_tmr(TimerHandle_t* tmr)
{
if (tmr && *tmr) {
xTimerStop(*tmr, portMAX_DELAY);
xTimerDelete(*tmr, portMAX_DELAY);
*tmr = NULL;
}
}
esp_err_t iot_button_delete(button_handle_t btn_handle)
{
POINT_ASSERT(TAG, btn_handle, ESP_ERR_INVALID_ARG);
button_dev_t* btn = (button_dev_t*) btn_handle;
gpio_set_intr_type(btn->io_num, GPIO_INTR_DISABLE);
gpio_isr_handler_remove(btn->io_num);
button_free_tmr(&btn->tap_rls_cb.tmr);
button_free_tmr(&btn->tap_psh_cb.tmr);
button_free_tmr(&btn->tap_short_cb.tmr);
button_free_tmr(&btn->press_serial_cb.tmr);
button_cb_t *pcb = btn->cb_head;
while (pcb != NULL) {
button_cb_t *cb_next = pcb->next_cb;
button_free_tmr(&pcb->tmr);
free(pcb);
pcb = cb_next;
}
free(btn);
return ESP_OK;
}
button_handle_t iot_button_create(gpio_num_t gpio_num, button_active_t active_level)
{
IOT_CHECK(TAG, gpio_num < GPIO_NUM_MAX, NULL);
button_dev_t* btn = (button_dev_t*) calloc(1, sizeof(button_dev_t));
POINT_ASSERT(TAG, btn, NULL);
btn->active_level = active_level;
btn->io_num = gpio_num;
btn->state = BUTTON_STATE_IDLE;
btn->taskq_on = 0;
btn->taskq = xQueueCreate(1, sizeof(void*));
btn->argq = xQueueCreate(1, sizeof(void *));
btn->tap_rls_cb.arg = NULL;
btn->tap_rls_cb.cb = NULL;
btn->tap_rls_cb.interval = BUTTON_GLITCH_FILTER_TIME_MS / portTICK_PERIOD_MS;
btn->tap_rls_cb.pbtn = btn;
btn->tap_rls_cb.tmr = xTimerCreate("btn_rls_tmr", btn->tap_rls_cb.interval, pdFALSE,
&btn->tap_rls_cb, button_tap_rls_cb);
btn->tap_psh_cb.arg = NULL;
btn->tap_psh_cb.cb = NULL;
btn->tap_psh_cb.interval = BUTTON_GLITCH_FILTER_TIME_MS / portTICK_PERIOD_MS;
btn->tap_psh_cb.pbtn = btn;
btn->tap_psh_cb.tmr = xTimerCreate("btn_psh_tmr", btn->tap_psh_cb.interval, pdFALSE,
&btn->tap_psh_cb, button_tap_psh_cb);
gpio_install_isr_service(0);
gpio_config_t gpio_conf;
gpio_conf.intr_type = GPIO_INTR_ANYEDGE;
gpio_conf.mode = GPIO_MODE_INPUT;
gpio_conf.pin_bit_mask = (uint64_t)1 << gpio_num;
gpio_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
gpio_conf.pull_up_en = GPIO_PULLUP_ENABLE;
gpio_config(&gpio_conf);
gpio_isr_handler_add(gpio_num, button_gpio_isr_handler, btn);
return (button_handle_t) btn;
}
esp_err_t iot_button_rm_cb(button_handle_t btn_handle, button_cb_type_t type)
{
button_dev_t* btn = (button_dev_t*) btn_handle;
button_cb_t* btn_cb = NULL;
if (type == BUTTON_CB_PUSH) {
btn_cb = &btn->tap_psh_cb;
} else if (type == BUTTON_CB_RELEASE) {
btn_cb = &btn->tap_rls_cb;
} else if (type == BUTTON_CB_TAP) {
btn_cb = &btn->tap_short_cb;
} else if (type == BUTTON_CB_SERIAL) {
btn_cb = &btn->press_serial_cb;
}
btn_cb->cb = NULL;
btn_cb->arg = NULL;
btn_cb->pbtn = btn;
button_free_tmr(&btn_cb->tmr);
return ESP_OK;
}
esp_err_t iot_button_set_serial_cb(button_handle_t btn_handle, uint32_t start_after_sec, TickType_t interval_tick, button_cb cb, void* arg)
{
button_dev_t* btn = (button_dev_t*) btn_handle;
btn->serial_thres_sec = start_after_sec;
if (btn->press_serial_cb.tmr == NULL) {
btn->press_serial_cb.tmr = xTimerCreate("btn_serial_tmr", btn->serial_thres_sec*1000 / portTICK_PERIOD_MS,
pdFALSE, btn, button_press_serial_cb);
}
btn->press_serial_cb.arg = arg;
btn->press_serial_cb.cb = cb;
btn->press_serial_cb.interval = interval_tick;
btn->press_serial_cb.pbtn = btn;
xTimerChangePeriod(btn->press_serial_cb.tmr, btn->serial_thres_sec*1000 / portTICK_PERIOD_MS, portMAX_DELAY);
return ESP_OK;
}
esp_err_t iot_button_set_evt_cb(button_handle_t btn_handle, button_cb_type_t type, button_cb cb, void* arg)
{
POINT_ASSERT(TAG, btn_handle, ESP_ERR_INVALID_ARG);
button_dev_t* btn = (button_dev_t*) btn_handle;
if (type == BUTTON_CB_PUSH) {
btn->tap_psh_cb.arg = arg;
btn->tap_psh_cb.cb = cb;
btn->tap_psh_cb.interval = BUTTON_GLITCH_FILTER_TIME_MS / portTICK_PERIOD_MS;
btn->tap_psh_cb.pbtn = btn;
xTimerChangePeriod(btn->tap_psh_cb.tmr, btn->tap_psh_cb.interval, portMAX_DELAY);
} else if (type == BUTTON_CB_RELEASE) {
btn->tap_rls_cb.arg = arg;
btn->tap_rls_cb.cb = cb;
btn->tap_rls_cb.interval = BUTTON_GLITCH_FILTER_TIME_MS / portTICK_PERIOD_MS;
btn->tap_rls_cb.pbtn = btn;
xTimerChangePeriod(btn->tap_rls_cb.tmr, btn->tap_psh_cb.interval, portMAX_DELAY);
} else if (type == BUTTON_CB_TAP) {
btn->tap_short_cb.arg = arg;
btn->tap_short_cb.cb = cb;
btn->tap_short_cb.interval = BUTTON_GLITCH_FILTER_TIME_MS / portTICK_PERIOD_MS;
btn->tap_short_cb.pbtn = btn;
} else if (type == BUTTON_CB_SERIAL) {
iot_button_set_serial_cb(btn_handle, 1, 1000 / portTICK_PERIOD_MS, cb, arg);
}
return ESP_OK;
}
esp_err_t iot_button_add_on_press_cb(button_handle_t btn_handle, uint32_t press_sec, button_cb cb, void* arg)
{
POINT_ASSERT(TAG, btn_handle, ESP_ERR_INVALID_ARG);
IOT_CHECK(TAG, press_sec != 0, ESP_ERR_INVALID_ARG);
button_dev_t* btn = (button_dev_t*) btn_handle;
button_cb_t* cb_new = (button_cb_t*) calloc(1, sizeof(button_cb_t));
POINT_ASSERT(TAG, cb_new, ESP_FAIL);
cb_new->on_press = 1;
cb_new->arg = arg;
cb_new->cb = cb;
cb_new->interval = press_sec * 1000 / portTICK_PERIOD_MS;
cb_new->pbtn = btn;
cb_new->tmr = xTimerCreate("btn_press_tmr", cb_new->interval, pdFALSE, cb_new, button_press_cb);
cb_new->next_cb = btn->cb_head;
btn->cb_head = cb_new;
return ESP_OK;
}
esp_err_t iot_button_add_on_release_cb(button_handle_t btn_handle, uint32_t press_sec, button_cb cb, void* arg)
{
POINT_ASSERT(TAG, btn_handle, ESP_ERR_INVALID_ARG);
IOT_CHECK(TAG, press_sec != 0, ESP_ERR_INVALID_ARG);
button_dev_t* btn = (button_dev_t*) btn_handle;
button_cb_t* cb_new = (button_cb_t*) calloc(1, sizeof(button_cb_t));
POINT_ASSERT(TAG, cb_new, ESP_FAIL);
btn->taskq_on = 1;
cb_new->arg = arg;
cb_new->cb = cb;
cb_new->interval = press_sec * 1000 / portTICK_PERIOD_MS;
cb_new->pbtn = btn;
cb_new->tmr = xTimerCreate("btn_press_tmr", cb_new->interval, pdFALSE, cb_new, button_press_cb);
cb_new->next_cb = btn->cb_head;
btn->cb_head = cb_new;
return ESP_OK;
}

View File

@@ -0,0 +1,54 @@
// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <esp_system.h>
#include <iot_button.h>
CButton::CButton(gpio_num_t gpio_num, button_active_t active_level)
{
m_btn_handle = iot_button_create(gpio_num, active_level);
}
CButton::~CButton()
{
iot_button_delete(m_btn_handle);
m_btn_handle = NULL;
}
esp_err_t CButton::set_evt_cb(button_cb_type_t type, button_cb cb, void* arg)
{
return iot_button_set_evt_cb(m_btn_handle, type, cb, arg);
}
esp_err_t CButton::set_serial_cb(button_cb cb, void* arg, TickType_t interval_tick, uint32_t start_after_sec)
{
return iot_button_set_serial_cb(m_btn_handle, start_after_sec, interval_tick, cb, arg);
}
esp_err_t CButton::add_on_press_cb(uint32_t press_sec, button_cb cb, void* arg)
{
return iot_button_add_on_press_cb(m_btn_handle, press_sec, cb, arg);
}
esp_err_t CButton::add_on_release_cb(uint32_t press_sec, button_cb cb, void* arg)
{
return iot_button_add_on_release_cb(m_btn_handle, press_sec, cb, arg);
}
esp_err_t CButton::rm_cb(button_cb_type_t type)
{
return iot_button_rm_cb(m_btn_handle, type);
}

View File

@@ -0,0 +1,272 @@
// Copyright 2020 Espressif Systems (Shanghai) PTE LTD
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef _IOT_BUTTON_H_
#define _IOT_BUTTON_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <driver/gpio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/portmacro.h>
typedef void (* button_cb)(void*);
typedef void* button_handle_t;
typedef enum {
BUTTON_ACTIVE_HIGH = 1, /*!<button active level: high level*/
BUTTON_ACTIVE_LOW = 0, /*!<button active level: low level*/
} button_active_t;
typedef enum {
BUTTON_CB_PUSH = 0, /*!<button push callback event */
BUTTON_CB_RELEASE, /*!<button release callback event */
BUTTON_CB_TAP, /*!<button quick tap callback event(will not trigger if there already is a "PRESS" event) */
BUTTON_CB_SERIAL, /*!<button serial trigger callback event */
} button_cb_type_t;
/**
* @brief Init button functions
*
* @param gpio_num GPIO index of the pin that the button uses
* @param active_level button hardware active level.
* For "BUTTON_ACTIVE_LOW" it means when the button pressed, the GPIO will read low level.
*
* @return A button_handle_t handle to the created button object, or NULL in case of error.
*/
button_handle_t iot_button_create(gpio_num_t gpio_num, button_active_t active_level);
/**
* @brief Register a callback function for a serial trigger event.
*
* @param btn_handle handle of the button object
* @param start_after_sec define the time after which to start serial trigger action
* @param interval_tick serial trigger interval
* @param cb callback function for "TAP" action.
* @param arg Parameter for callback function
* @note
* Button callback functions execute in the context of the timer service task.
* It is therefore essential that button callback functions never attempt to block.
* For example, a button callback function must not call vTaskDelay(), vTaskDelayUntil(),
* or specify a non zero block time when accessing a queue or a semaphore.
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t iot_button_set_serial_cb(button_handle_t btn_handle, uint32_t start_after_sec, TickType_t interval_tick, button_cb cb, void* arg);
/**
* @brief Register a callback function for a button_cb_type_t action.
*
* @param btn_handle handle of the button object
* @param type callback function type
* @param cb callback function for "TAP" action.
* @param arg Parameter for callback function
* @note
* Button callback functions execute in the context of the timer service task.
* It is therefore essential that button callback functions never attempt to block.
* For example, a button callback function must not call vTaskDelay(), vTaskDelayUntil(),
* or specify a non zero block time when accessing a queue or a semaphore.
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t iot_button_set_evt_cb(button_handle_t btn_handle, button_cb_type_t type, button_cb cb, void* arg);
/**
* @brief Callbacks invoked as timer events occur while button is pressed.
* Example: If a button is configured for 2 sec, 5 sec and 7 sec callbacks and if the button is pressed for 6 sec then 2 sec callback would be invoked at 2 sec event and 5 sec callback would be invoked at 5 sec event
*
* @param btn_handle handle of the button object
* @param press_sec the callback function would be called if you press the button for a specified period of time
* @param cb callback function for "PRESS and HOLD" action.
* @param arg Parameter for callback function
*
* @note
* Button callback functions execute in the context of the timer service task.
* It is therefore essential that button callback functions never attempt to block.
* For example, a button callback function must not call vTaskDelay(), vTaskDelayUntil(),
* or specify a non zero block time when accessing a queue or a semaphore.
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t iot_button_add_on_press_cb(button_handle_t btn_handle, uint32_t press_sec, button_cb cb, void* arg);
/**
* @brief Single callback invoked according to the latest timer event on button release.
* Example: If a button is configured for 2 sec, 5 sec and 7 sec callbacks and if the button is released at 6 sec then only 5 sec callback would be invoked
*
* @param btn_handle handle of the button object
* @param press_sec the callback function would be called if you press the button for a specified period of time
* @param cb callback function for "PRESS and RELEASE" action.
* @param arg Parameter for callback function
*
* @note
* Button callback functions execute in the context of the timer service task.
* It is therefore essential that button callback functions never attempt to block.
* For example, a button callback function must not call vTaskDelay(), vTaskDelayUntil(),
* or specify a non zero block time when accessing a queue or a semaphore.
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t iot_button_add_on_release_cb(button_handle_t btn_handle, uint32_t press_sec, button_cb cb, void* arg);
/**
* @brief Delete button object and free memory
* @param btn_handle handle of the button object
*
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t iot_button_delete(button_handle_t btn_handle);
/**
* @brief Remove callback
*
* @param btn_handle The handle of the button object
* @param type callback function event type
*
* @return
* - ESP_OK Success
*/
esp_err_t iot_button_rm_cb(button_handle_t btn_handle, button_cb_type_t type);
#ifdef __cplusplus
}
#endif
#ifdef __cplusplus
/**
* class of button
* simple usage:
* CButton* btn = new CButton(BUTTON_IO_NUM, BUTTON_ACTIVE_LEVEL, BUTTON_SERIAL_TRIGGER, 3);
* btn->add_cb(BUTTON_CB_PUSH, button_tap_cb, (void*) push, 50 / portTICK_PERIOD_MS);
* btn->add_custom_cb(5, button_press_5s_cb, NULL);
* ......
* delete btn;
*/
class CButton
{
private:
button_handle_t m_btn_handle;
/**
* prevent copy constructing
*/
CButton(const CButton&);
CButton& operator = (const CButton&);
public:
/**
* @brief constructor of CButton
*
* @param gpio_num GPIO index of the pin that the button uses
* @param active_level button hardware active level.
* For "BUTTON_ACTIVE_LOW" it means when the button pressed, the GPIO will read low level.
*/
CButton(gpio_num_t gpio_num, button_active_t active_level = BUTTON_ACTIVE_LOW);
~CButton();
/**
* @brief Register a callback function for a button_cb_type_t action.
*
* @param type callback function type
* @param cb callback function for "TAP" action.
* @param arg Parameter for callback function
* @note
* Button callback functions execute in the context of the timer service task.
* It is therefore essential that button callback functions never attempt to block.
* For example, a button callback function must not call vTaskDelay(), vTaskDelayUntil(),
* or specify a non zero block time when accessing a queue or a semaphore.
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t set_evt_cb(button_cb_type_t type, button_cb cb, void* arg);
/**
* @brief Register a callback function for a serial trigger event.
*
* @param btn_handle handle of the button object
* @param start_after_sec define the time after which to start serial trigger action
* @param interval_tick serial trigger interval
* @param cb callback function for "TAP" action.
* @param arg Parameter for callback function
* @note
* Button callback functions execute in the context of the timer service task.
* It is therefore essential that button callback functions never attempt to block.
* For example, a button callback function must not call vTaskDelay(), vTaskDelayUntil(),
* or specify a non zero block time when accessing a queue or a semaphore.
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t set_serial_cb(button_cb cb, void* arg, TickType_t interval_tick, uint32_t start_after_sec);
/**
* @brief Callbacks invoked as timer events occur while button is pressed
*
* @param press_sec the callback function would be called if you press the button for a specified period of time
* @param cb callback function for "PRESS and HOLD" action.
* @param arg Parameter for callback function
*
* @note
* Button callback functions execute in the context of the timer service task.
* It is therefore essential that button callback functions never attempt to block.
* For example, a button callback function must not call vTaskDelay(), vTaskDelayUntil(),
* or specify a non zero block time when accessing a queue or a semaphore.
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t add_on_press_cb(uint32_t press_sec, button_cb cb, void* arg);
/**
* @brief Single callback invoked according to the latest timer event on button release.
*
* @param press_sec the callback function would be called if you press the button for a specified period of time
* @param cb callback function for "PRESS and RELEASE" action.
* @param arg Parameter for callback function
*
* @note
* Button callback functions execute in the context of the timer service task.
* It is therefore essential that button callback functions never attempt to block.
* For example, a button callback function must not call vTaskDelay(), vTaskDelayUntil(),
* or specify a non zero block time when accessing a queue or a semaphore.
* @return
* - ESP_OK Success
* - ESP_FAIL Parameter error
*/
esp_err_t add_on_release_cb(uint32_t press_sec, button_cb cb, void* arg);
/**
* @brief Remove callback
*
* @param type callback function event type
*
* @return
* - ESP_OK Success
*/
esp_err_t rm_cb(button_cb_type_t type);
};
#endif
#endif

View File

@@ -0,0 +1,2 @@
COMPONENT_ADD_INCLUDEDIRS := ./button/include
COMPONENT_SRCDIRS := ./button

View File

@@ -0,0 +1,5 @@
set(srcs "ledc_driver.c")
idf_component_register(SRCS ${srcs}
INCLUDE_DIRS "."
PRIV_REQUIRES "driver")

View File

@@ -0,0 +1,2 @@
COMPONENT_ADD_INCLUDEDIRS := .
COMPONENT_SRCDIRS := .

View File

@@ -0,0 +1,179 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <stdio.h>
#include <freertos/FreeRTOS.h>
#include <freertos/task.h>
#include <driver/ledc.h>
#include <esp_err.h>
#include "ledc_driver.h"
/**
* @brief LEDC driver: Basic LEDC driver
*/
#define IS_ACTIVE_HIGH 0
#define LEDC_LS_TIMER LEDC_TIMER_0
#define LEDC_LS_MODE LEDC_LOW_SPEED_MODE
#define LEDC_LS_CH0_GPIO (0)
#define LEDC_LS_CH0_CHANNEL LEDC_CHANNEL_0
#define LEDC_LS_CH1_GPIO (1)
#define LEDC_LS_CH1_CHANNEL LEDC_CHANNEL_1
#define LEDC_LS_CH2_GPIO (8)
#define LEDC_LS_CH2_CHANNEL LEDC_CHANNEL_2
#define LEDC_NUM_CHANNELS (3)
#define LEDC_DUTY_RES LEDC_TIMER_13_BIT // Set duty resolution to 13 bits
#define LEDC_DUTY_MAX (8192 - 1) // (2 ** 13) - 1
#define LEDC_FREQUENCY (5000) // Frequency in Hertz. Set frequency at 5 kHz
/*
* Prepare individual configuration
* for each channel of LED Controller
* by selecting:
* - controller's channel number
* - output duty cycle, set initially to 0
* - GPIO number where LED is connected to
* - speed mode, either high or low
* - timer servicing selected channel
* Note: if different channels use one timer,
* then frequency and bit_num of these channels
* will be the same
*/
static ledc_channel_config_t ledc_channel[LEDC_NUM_CHANNELS] = {
{
.channel = LEDC_LS_CH0_CHANNEL,
.duty = 0,
.gpio_num = LEDC_LS_CH0_GPIO,
.speed_mode = LEDC_LS_MODE,
.hpoint = 0,
.timer_sel = LEDC_LS_TIMER,
},
{
.channel = LEDC_LS_CH1_CHANNEL,
.duty = 0,
.gpio_num = LEDC_LS_CH1_GPIO,
.speed_mode = LEDC_LS_MODE,
.hpoint = 0,
.timer_sel = LEDC_LS_TIMER, },
{
.channel = LEDC_LS_CH2_CHANNEL,
.duty = 0,
.gpio_num = LEDC_LS_CH2_GPIO,
.speed_mode = LEDC_LS_MODE,
.hpoint = 0,
.timer_sel = LEDC_LS_TIMER,
},
};
esp_err_t ledc_init(void)
{
/*
* Prepare and set configuration of timers
* that will be used by LED Controller
*/
ledc_timer_config_t ledc_timer = {
.duty_resolution = LEDC_DUTY_RES, // resolution of PWM duty
.freq_hz = LEDC_FREQUENCY, // frequency of PWM signal
.speed_mode = LEDC_LS_MODE, // timer mode
.timer_num = LEDC_LS_TIMER, // timer index
.clk_cfg = LEDC_AUTO_CLK, // Auto select the source clock
};
// Set configuration of timer0 for high speed channels
ledc_timer_config(&ledc_timer);
// Set LED Controller with previously prepared configuration
for (int ch = 0; ch < LEDC_NUM_CHANNELS; ch++) {
ledc_channel_config(&ledc_channel[ch]);
}
return ESP_OK;
}
static void ledc_hsv2rgb(uint32_t h, uint32_t s, uint32_t v, uint32_t *r, uint32_t *g, uint32_t *b)
{
h %= 360; // h -> [0,360]
uint32_t rgb_max = v * 2.55f;
uint32_t rgb_min = rgb_max * (100 - s) / 100.0f;
uint32_t i = h / 60;
uint32_t diff = h % 60;
// RGB adjustment amount by hue
uint32_t rgb_adj = (rgb_max - rgb_min) * diff / 60;
switch (i) {
case 0:
*r = rgb_max;
*g = rgb_min + rgb_adj;
*b = rgb_min;
break;
case 1:
*r = rgb_max - rgb_adj;
*g = rgb_max;
*b = rgb_min;
break;
case 2:
*r = rgb_min;
*g = rgb_max;
*b = rgb_min + rgb_adj;
break;
case 3:
*r = rgb_min;
*g = rgb_max - rgb_adj;
*b = rgb_max;
break;
case 4:
*r = rgb_min + rgb_adj;
*g = rgb_min;
*b = rgb_max;
break;
default:
*r = rgb_max;
*g = rgb_min;
*b = rgb_max - rgb_adj;
break;
}
}
esp_err_t ledc_set_rgb(uint32_t red, uint32_t green, uint32_t blue)
{
red = red * LEDC_DUTY_MAX / 255;
green = green * LEDC_DUTY_MAX / 255;
blue = blue * LEDC_DUTY_MAX / 255;
if (!IS_ACTIVE_HIGH) {
red = LEDC_DUTY_MAX - red;
green = LEDC_DUTY_MAX - green;
blue = LEDC_DUTY_MAX - blue;
}
ledc_set_duty(ledc_channel[0].speed_mode, ledc_channel[0].channel, red);
ledc_update_duty(ledc_channel[0].speed_mode, ledc_channel[0].channel);
ledc_set_duty(ledc_channel[1].speed_mode, ledc_channel[1].channel, green);
ledc_update_duty(ledc_channel[1].speed_mode, ledc_channel[1].channel);
ledc_set_duty(ledc_channel[2].speed_mode, ledc_channel[2].channel, blue);
ledc_update_duty(ledc_channel[2].speed_mode, ledc_channel[2].channel);
return ESP_OK;
}
esp_err_t ledc_set_hsv(uint32_t hue, uint32_t saturation, uint32_t value)
{
uint32_t red = 0;
uint32_t green = 0;
uint32_t blue = 0;
ledc_hsv2rgb(hue, saturation, value, &red, &green, &blue);
return ledc_set_rgb(red, green, blue);
}
esp_err_t ledc_clear()
{
return ledc_set_rgb(0, 0, 0);
return ESP_OK;
}

View File

@@ -0,0 +1,49 @@
/*
* SPDX-FileCopyrightText: 2024 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include <stdint.h>
/**
* @brief Initialize the LEDC RGB LED
*
* @return ESP_OK on success.
* @return error in case of failure.
*/
esp_err_t ledc_init(void);
/**
*
* @brief Set RGB value for the LED
*
* @param[in] red Intensity of Red color (0-100)
* @param[in] green Intensity of Green color (0-100)
* @param[in] blue Intensity of Green color (0-100)
*
* @return ESP_OK on success.
* @return error in case of failure.
*/
esp_err_t ledc_set_rgb(uint32_t red, uint32_t green, uint32_t blue);
/**
* @brief Set HSV value for the LED
*
* @param[in] hue Value of hue in arc degrees (0-360)
* @param[in] saturation Saturation in percentage (0-100)
* @param[in] value Value (also called Intensity) in percentage (0-100)
*
* @return ESP_OK on success.
* @return error in case of failure.
*/
esp_err_t ledc_set_hsv(uint32_t hue, uint32_t saturation, uint32_t value);
/**
* @brief Clear (turn off) the LED
* @return ESP_OK on success.
* @return error in case of failure.
*/
esp_err_t ledc_clear();

View File

@@ -0,0 +1,7 @@
set(srcs
"src/logger.c"
"src/output_buffer.c"
)
idf_component_register(SRCS "${srcs}"
INCLUDE_DIRS "include")

Some files were not shown because too many files have changed in this diff Show More