Add Library

This commit is contained in:
Siwat Sirichai 2019-08-09 09:01:56 +07:00
parent e365b9dbd9
commit 3c47103b39
318 changed files with 56465 additions and 0 deletions

View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://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 <http://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
<http://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
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -0,0 +1,159 @@
# ESP8266MQTTMesh
Self-assembling mesh network built around the MQTT protocol for the ESP8266 with OTA support
## Overview
This code provides a library that can build a mesh network between ESP8266 devices that will allow all nodes to communicate
with an MQTT broker. At least one node must be able to see a wiFi router, and there must me a host on the WiFi network running
the MQTT broker.
Nodes cannot (generally) communicate between themselves, but instead forward all messages through the broker.
Each node will expose a hidden AP which can be connected to from any other node on the network. Note: hiding the AP does not provide
any additional security, but does minimize the clutter of other WiFi clients in the area.
Additionally the library provides an OTA mechanism using the MQTT pathway which can update any/all nodes on the mesh.
This code was developed primarily for the Sonoff line of relays, but should work with any ESP8266 board with sufficient flash memory
Further information about the mesh topology can be found [here](docs/MeshTopology.md)
### Note for version >= 1.0
As of version 1.0 the nodes no longer need to connect to the broker once before use. Nodes can self-identify other nodes automatically
and do not store any needed state on the broker. Nodes use the MAC address to identify other nodes, and the ESP8266MQTTMesh code
will change the node's MAC address to match the required pattern. The MAC addresses are based on both the node's chipID as well as the mesh password, ensuring that each node will have a unique MAC address as well as that multiple meshes can run in the same area independently.
Also, he ESP8266MQTTMesh code no longer uses the SPIFFS file-system. If you need it, you'll need to initialize it yourself. If
the mesh is configured to use SSL between nodes, the SSL certs need to be provided during initalization
## OTA
While all nodes must run the same version of the ESP8622MQTTMesh library, each node may run a unique firmware with independent purposes.
The main purpose behind this library was to provide a backbone on which several home-automation sensors could be built. As such
each node may need different code to achieve its purpose. Because firmwares are large, and memory is limited on the ESP8266 platform,
there is only a single memory area to hold the incoming firmware. To ensure that a given firmware is only consumed by the proper nodes,
The firmware defines a unique identifier that distinguishes itself from other code. A given firmware is broadcast from the MQTT
broker to all nodes, but only nodes with a matching ID will update.
## Using the Library
### Prerequisites
This library has been converted to use Asynchronous communication for imroved reliability. It requires the following libraries to be installed
* AsyncMqttClient
* ESPAsyncTCP
* Arduino ESP8266 Core version 2.4
PlatformIO is strongly recommended, and installation instructions can be found [here](http://docs.platformio.org/en/latest/platforms/espressif8266.html)).
**NOTE:** Enabling SSL will add ~70kB to the firmware size, and may make it impossible to use OTA updates depending on firmware and flash size.
If OTA support is desired, the esp8266 module must have at least 1M or Flash (configured as >=784k ROM). The OTA image is stored
between the end of the firmware image and the beginning of the filesystem (i.e. not in the filesystem itself) or the end of flash if
no filesystem is present. Thus, ithe maximum firmware size is ~ 1/2 the available Flash.
### Library initialization
The ESP8266MQTTMesh only requires 2 parameters to initialize, but there are many additional optional parameters:
```
ESP8266MQTTMesh mesh = ESP8266MQTTMesh::Builder(networks, mqtt_server, mqtt_port).build();
```
- `wifi_conn networks[]` *Required*: A list of SSIDs/BSSIDs/passwords to search for to connect to the wireless network. The list should be terminated with a NULL element.
- `const char *mqtt_server` *Required*: Host which runs the MQTT broker
- `int mqtt_port` *Optional*: Port which the MQTT broker is running on. Defaults to 1883 if MQTT SSL is not enabled. Defaults to 8883 is MQTT SSL is enabled
Additional Parameters can be enabled via the *Builder* for example:
```
ESP8266MQTTMesh mesh = ESP8266MQTTMesh::Builder(networks, mqtt_server, mqtt_port)
.setVersion(firmware_ver, firmware_id)
.setMeshPassword(password)
.build();
```
These additional parameters are specified before calling build(), and as few or as many can be used as neeeded.
```
setVersion(firmware_ver, firmware_id)
```
- `const char *firmware_ver`: This is a string that idenitfies the firmware. It can be whatever you like. It will be broadcast to the MQTT broker on successful connection
- `int firmware_id`: This identifies a specific node codebase. Each unique firmware should have its own id, and it should not be changed between revisions of the code
```
setMqttAuth(username, password)
```
- `const char *username`: The username used to login to the MQTT broker
- `const char *password`: The password used to login to the MQTT broker
```
setMeshPassword(password)
```
- `const char *password`: The password to use when a node connects to another node on the mesh. Default: `ESP8266MQTTMesh`
```
setMeshSSID(ssid)
```
- `const char *ssid`: The SSID used by mesh nodes. All nodes will use the same SSID, though this isn't noticeable due to nodes using hidden networks. Default: `esp8266_mqtt_mesh
```
setMeshPort(port)
```
- `int port`: Port for mesh nodes to listen on for message parsing. Default: `1884`
```
setTopic(in_topic, out_topic)
```
- `const char *in_topic`: MQTT topic prefix for messages sent to the node. Default: `esp8266-in/`
- `const char *out_topic`: MQTT topic prefix for messages from the node. Default: `esp8266-out/`
If SSL support is enabled, the following optional parameters are available:
```
setMqttSSL(enable, fingerprint)
```
- `bool enable`: Enable MQTT SSL support. Default: `false`
- `const uint8_t *fingerprint`: Fingerprint to verify MQTT certificate (prevent man-in-the-middle attacks)
```
setMeshSSL(cert, cert_len, key, key_len, fingerprint)
```
- `const uint8_t *cert`: Certificate
- `uint32_t cert_len`: Certificate length
- `const uint8_t *key`: Certificate key
- `uint32_t key_len`: Certificate key length
- `uint8_t *fingerprint`: Certificate fingerprint (SHA1 of certificate)
### Interacting with the mesh
Besides the constructor, the code must call the `begin()` method during setup, and the `loop()` method in the main loop
If messages need to be received by the node, execute the `callback()` function during setup with a function pointer
(prototype: `void callback(const char *topic, const char *payload)`)
To send messages to the MQTT broker, use one of the publish methods:
```
publish(topic, payload, msgCmd)
publish_node(topic, payload, msgCmd)
```
The `publish` function sends messages with the `out_topic` prefix, and will not be relayed to any nodes. The `publish_nodes`
function will send messages with the `in_topic` prefix and will be relayed back to all nodes
- `const char *topic`: the message topic (will be appended to the topic-prefix)
- `const char *payload`: The message to send (must be less than 1152 bytes in length)
- `enum MSG_TYPE msgCmd`: The MQTT Retail/QoS partameters (optional). Must be one of: `MSG_TYPE_NONE`,
`MSG_TYPE_QOS_0`, `MSG_TYPE_QOS_1`, `MSG_TYPE_QOS_2`, `MSG_TYPE_RETAIN_QOS_0`, MSG_TYPE_RETAIN_QOS_1`,
`MSG_TYPE_RETAIN_QOS_2`. Default: `MSG_TYPE_NONE`
### SSL support
SSL support is enabled by defining `ASYNC_TCP_SSL_ENABLED=1`. This must be done globally during build.
Once enabled, SSL can be optionally enabled between the node and the MQTT broker or between mesh nodes (or both).
#### Using SSL with the MQTT Broker
**WARNING:** Make sure you do not use SHA512 certificate signatures on your MQTT broker. They are not suppoorted by ESP8266 properly
Using an optional fingerprint ensures that the MQTT Broker is the one you expect. Specifying a fingerprint is useful to prevent man-in-the-middle attacks.
The fingerprint can be generated by running:
```
utils/get_mqtt_fingerprint.py --host <MQTT host> --post <MQTT port>
```
This will also check the signature to make sure it is compatible with ESP8266
#### Using SSL between mesh nodes
**NOTE:** Enabling SSL between mesh nodes should not provide additional security, since the mesh connections are already secured via WPA, so enabling this is not recommended
Generate the certificate, key and fingerprint:
```
utils/gen_server_cert.sh
```
Add the resulting ssl_cert.h to your project. then add to the Builder `setMeshSSL(ssl_cert, ssl_cert_len, ssl_key, ssl_key_len, ssl_fingerprint)`

View file

@ -0,0 +1,25 @@
# Mesh Construction and Communication
![Mesh Topology](images/MeshTopology.png)
Nodes always power up in Station mode. Each node in the mesh will 1st try to connect to one of the configured WiFi access-points.i
If the node cannot see any APs, it will next attempt to connect to any nearby nodes.
A potential node is identified by having a hidden SSID and having a specific MAC address.
Each node constructs its MAC address by combining its chipId (upper 3 octets) with the mesh password and generating the lower 3 octets.
The connecting node will check each hidden network's MAC address by calculating the lower 3 octets and verifying that they match the
AP. All matching nodes are sorted by signal strength, and the node will attempt to connect to each in order.
Once connected, the connecting node will then open a RCP connection on the specified port, and send the mesh password to the AP. Next the
node will broadcast a MQTT message about its availability (ex `esp8266-out/bssid/aabbcc=00:11:22:33:44:55`). This message is sent with the
retain bit set to preserve it on the broker, but it is never consumed by any other nodes. Lastly, the node will start its own AP and begin
listening for connections from other nodes.
Each node can only handle 4 incoming commections, and will refuse connections once it has reached the limit. While the max connection
count is limited by the ESP8266 core code. The ESP8266MQTTMesh library also assumes this limit.
If a node loses its connection to the AP, it will also shutdown its own AP. This will result in the subsection of the mesh reorganizing
and rebuilding automatically. It is required that at least one node can see the WiFi AP at any time as the broker must be available
to handle message passing.
Mesh nodes cannot generally communicate directly with each other. Instead all messages are passed through the MQTT broker. Nodes
automatically subscribe to all topics beginning with the `in_topic` value (typically `esp8266-in/`).

Binary file not shown.

After

Width:  |  Height:  |  Size: 80 KiB

View file

@ -0,0 +1,34 @@
# ESP8266MeshHelloWorld
This is a trivial node that can be used to test the mesh network.
## Configuration
a sample configuration is provided in `src/credentials.h.example`.
1) First copy `src/credentials.h.example` to `src/credentials.h`
2) Edit `credentials.h` and modify the configuration to suit your environment
The following variables should be set:
- *NETWORK_PASSWORD* : Specifies the password of your wireless network
- *NETWORK_LIST* : Specifies the SSIDs of your wireless network
- *MQTT_SERVER* : Specify the IP address of your MQTT broker
- *MQTT_PORT* : Specify the port of your MQTT broker
The following can optionally be changed:
- *MESH_PASSWORD* : A string used by all nodes to prevent unauthorized access to the mesh network
- *MESH_PORT* : The port that the mesh nodes listen on
These options are only relevant if the node is compiled with SSL enabled:
- *MESH_SECURE* : Enable SSL bewteen mesh nodes. This requires that the `ssl_cert.h` file is present (Use [this](https://github.com/marvinroger/async-mqtt-client/blob/master/scripts/gen_server_cert.sh) script to generate this header)
- *MQTT_SECURE* : Enable SSL connection to the MQTT broker.
- *MQTT_FINGERPRINT* : a 20-byte string that uniquely identifies your MQTTbroker. A script to retrieve the fingerprint can be found [here](https://github.com/marvinroger/async-mqtt-client/blob/master/scripts/get-fingerprint/get-fingerprint.py)
## Compiling and uploading
This example has been designed to use platformio for building and install
Assuming you have already setup a platformio environment:
### Non-SSL
`platformio run --target upload`
### SSL (Still experimental)
`platformio run -e ssl --target upload`

View file

@ -0,0 +1 @@
<EFBFBD><03><>Ѝ<EFBFBD><D08D><11><>,WN<57><4E>H,5d

View file

@ -0,0 +1,39 @@
#
# Example PlatformIO configuration file for SSL and non-SSL builds.
#
# Before you will be able to build the SSL version of this project, you will
# need to explicitly install the espressif8266_stage platform.
#
# To perform this installation, refer to step 1 of:
# http://docs.platformio.org/en/latest/platforms/espressif8266.html#using-arduino-framework-with-staging-version
[platformio]
env_default = nossl
[common]
framework = arduino
lib_deps = ESP8266MQTTMesh
[env:nossl]
#platform = https://github.com/platformio/platform-espressif8266.git#feature/stage
platform = espressif8266@~1.6.0
board = esp01_1m
framework = ${common.framework}
lib_deps = ${common.lib_deps}
#build_flags = -DLED_PIN=2 -g
[env:ssl]
platform = espressif8266@~1.6.0
board = esp01_1m
#build_flags = -DASYNC_TCP_SSL_ENABLED=1 -DGATEWAY_ID=10499051 -DLED_PIN=2 -g
build_flags = -DASYNC_TCP_SSL_ENABLED=1
framework = ${common.framework}
lib_deps = ${common.lib_deps}
[env:esp32_nossl]
platform = espressif32
board = esp32dev
framework = ${common.framework}
lib_deps = ${common.lib_deps}
build_flags = -DLED_PIN=2 -g

View file

@ -0,0 +1,98 @@
#include "credentials.h"
#include <ESP8266MQTTMesh.h>
#include <FS.h>
#ifndef LED_PIN
#define LED_PIN LED_BUILTIN
#endif
#define FIRMWARE_ID 0x1337
#define FIRMWARE_VER "0.1"
wifi_conn networks[] = NETWORK_LIST;
const char* mesh_password = MESH_PASSWORD;
const char* mqtt_server = MQTT_SERVER;
const int mqtt_port = MQTT_PORT;
#if ASYNC_TCP_SSL_ENABLED
const uint8_t *mqtt_fingerprint = MQTT_FINGERPRINT;
bool mqtt_secure = MQTT_SECURE;
#if MESH_SECURE
#include "ssl_cert.h"
#endif
#endif
#ifdef ESP32
String ID = String((unsigned long)ESP.getEfuseMac());
#else
String ID = String(ESP.getChipId());
#endif
unsigned long previousMillis = 0;
const long interval = 5000;
int cnt = 0;
// Note: All of the '.set' options below are optional. The default values can be
// found in ESP8266MQTTMeshBuilder.h
ESP8266MQTTMesh mesh = ESP8266MQTTMesh::Builder(networks, mqtt_server, mqtt_port)
.setVersion(FIRMWARE_VER, FIRMWARE_ID)
.setMeshPassword(mesh_password)
#if ASYNC_TCP_SSL_ENABLED
.setMqttSSL(mqtt_secure, mqtt_fingerprint)
#if MESH_SECURE
.setMeshSSL(ssl_cert, ssl_cert_len, ssl_key, ssl_key_len, ssl_fingerprint)
#endif //MESH_SECURE
#endif //ASYNC_TCP_SSL_ENABLED
.build();
void callback(const char *topic, const char *msg);
void setup() {
Serial.begin(115200);
delay(1000); //This is only here to make it easier to catch the startup messages. It isn't required
mesh.setCallback(callback);
mesh.begin();
pinMode(LED_PIN, OUTPUT);
}
void loop() {
if (! mesh.connected())
return;
unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
String cntStr = String(cnt);
String msg = "hello from " + ID + " cnt: " + cntStr;
mesh.publish(ID.c_str(), msg.c_str());
previousMillis = currentMillis;
cnt++;
}
}
void callback(const char *topic, const char *msg) {
if (0 == strcmp(topic, (const char*) ID.c_str())) {
if(String(msg) == "0") {
digitalWrite(LED_PIN, HIGH);
}else{
digitalWrite(LED_PIN, LOW);
}
}
}

View file

@ -0,0 +1,16 @@
#define NETWORK_PASSWORD "network password"
#define NETWORK_LIST { \
WIFI_CONN("ssid 1", NETWORK_PASSWORD, NULL, 0), \
WIFI_CONN("ssid 2", NETWORK_PASSWORD, NULL, 0), \
NULL, \
}
#define MESH_PASSWORD "esp8266_sensor_mesh"
#define MQTT_SERVER "MQTT Server IP Address"
#define MQTT_PORT 1883
/* Only used if SSL is enabled */
#define MESH_SECURE true
#define MQTT_SECURE false
#define MQTT_FINGERPRINT NULL
//const uint8_t MQTT_FINGERPRINT[] = {0x00,0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x88,0x99,0xaa,0xbb,0xcc,0xdd,0xee,0xff,0x00,0x11,0x22,0x33};

View file

@ -0,0 +1,87 @@
const uint8_t ssl_key[] =
"\x30\x82\x02\x5D\x02\x01\x00\x02\x81\x81\x00\xA6\xE5\xE8\x1A\xFB"
"\xF8\x1A\xB7\x34\xCF\x98\x90\x10\x7A\x80\x1D\x1C\x3F\xA7\x9A\xC0"
"\x97\x5D\xC2\xCF\xD0\xD6\xCE\x65\x11\x57\xB5\x4A\x21\x81\x5E\x66"
"\xBE\x05\x70\xDC\xF3\x5C\x8D\x40\x12\x03\x22\xAC\x75\x26\x92\x04"
"\x1F\xC1\x9D\x6F\x68\x4E\x70\xE9\x43\xF1\xD0\xF2\x2F\x68\xDE\xA5"
"\x9A\xBA\xF6\xCA\x53\xA4\x89\x49\xD8\x9C\x65\x7C\x02\x7B\xBF\xFC"
"\x66\x56\xA6\x55\x45\x71\x8B\x31\x3F\xEC\xA0\x65\x0B\x76\x6F\xE5"
"\x08\x67\xDF\x8A\x9E\x8B\x46\x29\x63\x71\x84\xED\x57\xC2\xBC\x37"
"\x79\xA2\x3F\xFA\x39\xD3\xEA\xBF\x7A\xCB\x83\x02\x03\x01\x00\x01"
"\x02\x81\x80\x21\xCB\x2F\xA2\x37\x1E\xD7\x99\xFD\x11\x83\xDC\xB7"
"\xD9\x76\x13\x6E\xE2\xDC\xB7\x13\x04\x13\x32\x1D\x0E\x36\x50\x78"
"\x5A\x78\x9D\xF6\xB2\xAE\x15\x45\x4C\x78\xA1\x8F\xBB\x9F\x23\xE2"
"\xB3\x42\xFB\x44\x5C\x3C\x41\x18\xA0\xAD\x7D\x89\x4F\x5F\x82\xB1"
"\x58\xD6\x9F\x9A\x8F\x3A\x2C\x5C\xE4\xED\xEC\x5E\x95\xDB\x59\x66"
"\xEE\xF3\xAB\x95\x3E\x3D\xF6\xC0\xFD\x13\x38\x78\x1D\xC8\xE2\x08"
"\xAC\x3B\xA5\x1F\xC8\x64\xD2\xD2\xC4\x3E\xD1\xC0\x4B\xC2\xC8\x56"
"\x94\xC1\xE5\xA1\x5C\x57\x7E\x56\x5E\xC1\x33\x80\x7F\x07\x33\xD8"
"\x0B\xD5\xC1\x02\x41\x00\xD3\x95\x14\xE1\xC1\xAB\xEF\x19\x66\x6C"
"\xFE\xDB\xB3\x75\xD0\xEA\x1C\x2C\x17\x2A\x3F\x6D\x79\xCA\xA9\x82"
"\x7F\x19\x98\xC0\x1F\x96\x0A\x6B\x86\x01\xAE\x4E\xEA\x99\x48\x65"
"\x61\xC8\xB1\xC1\xDC\x20\xFF\xEE\x3A\xB3\x10\xCE\x4B\xEF\x6C\xD0"
"\x60\x44\x68\x33\x45\x13\x02\x41\x00\xC9\xEF\x63\xDA\x7D\xF8\x8A"
"\xC9\xD1\x96\xBE\x13\xB6\x3F\xB6\x04\xF1\xD7\x06\x89\xCC\x2D\x5E"
"\xDA\x9A\x78\xA7\xAC\x40\x37\x2E\x5C\x1F\x7C\x64\x6D\x4B\xB1\x78"
"\xD6\x62\x5F\x60\x95\xC9\x7B\xD7\x03\x54\x46\x98\xD8\x4E\xA8\xB8"
"\xC6\x32\xD8\xC5\x32\xAE\xCA\xDD\xD1\x02\x40\x57\x37\x61\xF7\x39"
"\x85\x6D\x37\x14\x30\xA3\xD1\xDE\xA5\x17\x2C\x19\xD6\xD6\xE9\xB4"
"\x61\xA5\x4D\xB4\x18\x35\xDA\x50\x4C\x09\xF9\x28\x6C\x70\x3D\xEB"
"\x23\x5E\xB3\x36\xD3\x8B\xBE\x55\xFF\xEA\x84\xB3\xDA\xF8\xD9\x6D"
"\x79\x0C\x76\x32\x6D\xA6\xF1\x2B\xDE\xCE\x7F\x02\x41\x00\x89\xD6"
"\x0B\xB4\x92\x13\xDA\xB8\x53\x85\xAF\x8C\xC8\xF3\xC8\x0C\xAB\xFE"
"\xF8\x09\x8B\x02\xD5\x22\x26\x1A\x81\x69\x04\x14\x26\x62\xDF\x63"
"\x0B\x31\xC7\x5F\x06\x7A\x5F\x7F\x76\xF0\x07\x2D\xAE\xE0\x28\xE0"
"\x5F\x68\x16\x98\xF8\x36\xE1\x72\x31\x78\x9C\xF3\x00\x61\x02\x41"
"\x00\xB5\x07\xCF\xC3\x62\x65\xD3\xD4\x97\x2B\xCA\x6B\x66\x75\x5C"
"\xE1\x38\xFD\xAF\xC2\xA9\xCE\x21\x3F\x09\xDC\xEA\xEE\xD2\x09\xF8"
"\xCF\xF6\x8D\xEC\x95\xF2\x12\xAC\xE7\x11\x30\xE3\xC6\xDB\x26\x17"
"\x64\xB1\xC2\x78\xF0\x47\x75\x11\xA9\x69\x52\x23\xC3\x2B\x37\x4B"
"\xBB"
;
const uint32_t ssl_key_len = 609;
const uint8_t ssl_cert[] =
"\x30\x82\x02\x47\x30\x82\x01\x2F\x02\x09\x00\xD2\x15\x44\x99\x56"
"\xC9\xF0\xD1\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x01\x05"
"\x05\x00\x30\x1C\x31\x1A\x30\x18\x06\x03\x55\x04\x0A\x0C\x11\x45"
"\x73\x70\x72\x65\x73\x73\x69\x66\x20\x53\x79\x73\x74\x65\x6D\x73"
"\x30\x1E\x17\x0D\x31\x37\x30\x37\x31\x31\x30\x33\x30\x33\x31\x32"
"\x5A\x17\x0D\x33\x31\x30\x33\x32\x30\x30\x33\x30\x33\x31\x32\x5A"
"\x30\x33\x31\x19\x30\x17\x06\x03\x55\x04\x0A\x0C\x10\x61\x78\x54"
"\x4C\x53\x20\x6F\x6E\x20\x45\x53\x50\x38\x32\x36\x36\x31\x16\x30"
"\x14\x06\x03\x55\x04\x03\x0C\x0D\x65\x73\x70\x38\x32\x36\x36\x2E"
"\x6C\x6F\x63\x61\x6C\x30\x81\x9F\x30\x0D\x06\x09\x2A\x86\x48\x86"
"\xF7\x0D\x01\x01\x01\x05\x00\x03\x81\x8D\x00\x30\x81\x89\x02\x81"
"\x81\x00\xA6\xE5\xE8\x1A\xFB\xF8\x1A\xB7\x34\xCF\x98\x90\x10\x7A"
"\x80\x1D\x1C\x3F\xA7\x9A\xC0\x97\x5D\xC2\xCF\xD0\xD6\xCE\x65\x11"
"\x57\xB5\x4A\x21\x81\x5E\x66\xBE\x05\x70\xDC\xF3\x5C\x8D\x40\x12"
"\x03\x22\xAC\x75\x26\x92\x04\x1F\xC1\x9D\x6F\x68\x4E\x70\xE9\x43"
"\xF1\xD0\xF2\x2F\x68\xDE\xA5\x9A\xBA\xF6\xCA\x53\xA4\x89\x49\xD8"
"\x9C\x65\x7C\x02\x7B\xBF\xFC\x66\x56\xA6\x55\x45\x71\x8B\x31\x3F"
"\xEC\xA0\x65\x0B\x76\x6F\xE5\x08\x67\xDF\x8A\x9E\x8B\x46\x29\x63"
"\x71\x84\xED\x57\xC2\xBC\x37\x79\xA2\x3F\xFA\x39\xD3\xEA\xBF\x7A"
"\xCB\x83\x02\x03\x01\x00\x01\x30\x0D\x06\x09\x2A\x86\x48\x86\xF7"
"\x0D\x01\x01\x05\x05\x00\x03\x82\x01\x01\x00\x5F\x4F\xA6\x53\x1D"
"\xC2\x7C\x2C\x0D\xDE\x54\x05\xAD\x61\xDE\x39\xE2\x8B\xA9\x47\x0D"
"\x57\xC3\xC0\x15\x18\x0C\xBF\x71\x32\x5A\x8E\x68\x64\x7A\xA2\xE3"
"\x27\x76\xC4\x22\x16\x31\x7A\x14\xD7\x2B\x16\x1E\x94\x2F\x69\x51"
"\xFF\xE0\xBC\x84\xD7\x6B\x51\xC1\xA7\x45\x1E\x6E\xB4\x86\x4F\xDD"
"\x07\x15\x72\x4B\x12\x79\xEF\x31\xDE\xE4\x9E\xC6\x6F\xDA\x36\xC8"
"\x59\x1B\x6A\x3E\xF0\xDE\xD7\x84\xCE\xE7\xAE\x59\xBE\xB6\x2D\xB0"
"\xD3\x84\x8F\xD6\xA2\x6F\x2F\x9E\x22\x5B\x1D\x61\xCF\x96\xB3\x62"
"\x16\x63\xC7\x8A\xA8\xC8\x7C\xE0\xB5\x98\xAE\x12\xB1\xAE\xE5\xFF"
"\x1F\x1A\x0D\x15\x7C\x26\xF0\x19\xBF\x12\x70\xB3\x29\xF1\xA0\x14"
"\x64\x52\x08\x56\x88\xBF\x54\xCF\x5C\x44\x50\x25\xB9\xF4\xC3\x29"
"\x3B\xB2\x98\xC8\xE2\xB9\x76\x78\x0E\xDB\x8E\x52\x8B\x4D\x7B\x95"
"\xDB\xCB\xE8\x68\x67\x3B\x6F\x99\x0E\xDC\x4D\x81\x93\xB2\xA3\x99"
"\xD2\xBC\x1E\xB4\x4F\x9D\xC0\x11\xEF\x10\xD4\xA8\x32\xEC\xE3\xFE"
"\xA8\x52\x57\x4F\x04\x3D\x17\x9B\xF1\x3C\x19\xAB\x17\x03\x66\x69"
"\x90\x8A\x7B\x09\xDF\xF9\x78\xE6\xC6\xED\x04\x19\x2B\x88\xD4\xE1"
"\x80\x88\x1A\x98\x6F\x9C\x6D\x37\x18\x55\x36"
;
const uint32_t ssl_cert_len = 587;
const uint8_t ssl_fingerprint[] =
"\xC8\x03\xFF\xF8\xD0\x8D\xB8\xE7\x11\xF0\x87\x2C\x57\x4E\xDD\xD3"
"\x48\x2C\x35\x64"
;

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,441 @@
#====================================================================================
# makeESPArduino
#
# A makefile for ESP8286 and ESP32 Arduino projects.
# Edit the contents of this file to suit your project
# or just include it and override the applicable macros.
#
# License: GPL 2.1
# General and full license information is available at:
# https://github.com/plerup/makeEspArduino
#
# Copyright (c) 2016-2017 Peter Lerup. All rights reserved.
#
#====================================================================================
#====================================================================================
# Project specfic values
#====================================================================================
# Include possible project makefile. This can be used to override the defaults below
-include $(firstword $(PROJ_CONF) $(dir $(SKETCH))config.mk)
#=== Default values not available in the Arduino configuration files
CHIP ?= esp8266
# Set chip specific default board unless specified
BOARD ?= $(if $(filter $(CHIP), esp32),esp32,generic)
# Serial flashing parameters
UPLOAD_PORT ?= $(shell ls -1tr /dev/ttyUSB* | tail -1)
UPLOAD_VERB ?= -v
# OTA parameters
ESP_ADDR ?= ESP_123456
ESP_PORT ?= 8266
ESP_PWD ?= 123
# HTTP update parameters
HTTP_ADDR ?= ESP_123456
HTTP_URI ?= /update
HTTP_PWD ?= user
HTTP_USR ?= password
# Output directory
BUILD_DIR ?= /tmp/mkESP/$(MAIN_NAME)_$(BOARD)
# File system source directory
FS_DIR ?= $(dir $(SKETCH))data
# Bootloader
BOOT_LOADER ?= $(ESP_ROOT)/bootloaders/eboot/eboot.elf
#====================================================================================
# Standard build logic and values
#====================================================================================
START_TIME := $(shell perl -e "print time();")
# Utility functions
git_description = $(shell git -C $(1) describe --tags --always --dirty 2>/dev/null || echo Unknown)
time_string = $(shell date +$(1))
# ESP Arduino directories
ifndef ESP_ROOT
# Location not defined, find and use possible version in the Arduino IDE installation
OS ?= $(shell uname -s)
ifeq ($(OS), Windows_NT)
ARDUINO_DIR = $(shell cygpath -m $(LOCALAPPDATA)/Arduino15/packages/$(CHIP))
else ifeq ($(OS), Darwin)
ARDUINO_DIR = $(HOME)/Library/Arduino15/packages/$(CHIP)
else
ARDUINO_DIR = $(HOME)/.arduino15/packages/$(CHIP)
endif
ESP_ROOT := $(lastword $(wildcard $(ARDUINO_DIR)/hardware/$(CHIP)/*))
ifeq ($(ESP_ROOT),)
$(error No installed version of $(CHIP) Arduino found)
endif
ESP_ARDUINO_VERSION := $(notdir $(ESP_ROOT))
# Find used version of compiler and tools
COMP_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/xtensa-lx106-elf-gcc/*))
ESPTOOL_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/esptool/*))
MKSPIFFS_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/mkspiffs/*))
else
# Location defined, assume it is a git clone
ESP_ARDUINO_VERSION = $(call git_description,$(ESP_ROOT))
endif
ESP_LIBS = $(ESP_ROOT)/libraries
SDK_ROOT = $(ESP_ROOT)/tools/sdk
TOOLS_ROOT = $(ESP_ROOT)/tools
ifeq ($(wildcard $(ESP_ROOT)/cores/$(CHIP)),)
$(error $(ESP_ROOT) is not a vaild directory for $(CHIP))
endif
ESPTOOL_PY = esptool.py --baud=$(UPLOAD_SPEED) --port $(UPLOAD_PORT)
# Search for sketch if not defined
SKETCH := $(realpath $(firstword \
$(SKETCH) \
$(wildcard *.ino) \
$(if $(filter $(CHIP), esp32),$(ESP_LIBS)/WiFi/examples/WiFiScan/WiFiScan.ino,$(ESP_LIBS)/ESP8266WebServer/examples/HelloServer/HelloServer.ino) \
) \
)
ifeq ($(wildcard $(SKETCH)),)
$(error Sketch $(SKETCH) not found)
endif
# Main output definitions
MAIN_NAME := $(basename $(notdir $(SKETCH)))
MAIN_EXE = $(BUILD_DIR)/$(MAIN_NAME).bin
FS_IMAGE = $(BUILD_DIR)/FS.spiffs
ifeq ($(OS), Windows_NT)
# Adjust critical paths
BUILD_DIR := $(shell cygpath -m $(BUILD_DIR))
SKETCH := $(shell cygpath -m $(SKETCH))
endif
# Build file extensions
OBJ_EXT = .o
DEP_EXT = .d
# Special tool definitions
OTA_TOOL ?= $(TOOLS_ROOT)/espota.py
HTTP_TOOL ?= curl
# Core source files
CORE_DIR = $(ESP_ROOT)/cores/$(CHIP)
CORE_SRC := $(shell find $(CORE_DIR) -name "*.S" -o -name "*.c" -o -name "*.cpp")
CORE_OBJ := $(patsubst %,$(BUILD_DIR)/%$(OBJ_EXT),$(notdir $(CORE_SRC)))
CORE_LIB = $(BUILD_DIR)/arduino.ar
# User defined compilation units and directories
ifeq ($(LIBS),)
# Automatically find directories with header files used by the sketch
FINDCMD := perl -e 'use File::Find;@d = split(" ", shift);while (<>) {$$f{"$$1"} = 1 if /^\s*\#include\s+[<"]([^>"]+)/;}find({follow => 1, wanted => sub {return if($$File::Find::dir =~ /examples|tests/);print $$File::Find::dir," " if $$f{$$_}}}, @d);'
LIBS := $(shell $(FINDCMD) "$(ESP_LIBS) $(HOME)/Arduino/libraries" $(SKETCH) ../../src/*.cpp ../../src/*.h)
ifeq ($(LIBS),)
# No dependencies found
LIBS = /dev/null
endif
endif
IGNORE_PATTERN := $(foreach dir,$(EXCLUDE_DIRS),$(dir)/%)
SKETCH_DIR = $(dir $(SKETCH))
USER_INC := $(filter-out $(IGNORE_PATTERN),$(shell find -L $(SKETCH_DIR) $(LIBS) -name "*.h"))
USER_SRC := $(SKETCH) $(filter-out $(IGNORE_PATTERN),$(shell find -L $(SKETCH_DIR) $(LIBS) -name "*.S" -o -name "*.c" -o -name "*.cpp"))
# Object file suffix seems to be significant for the linker...
USER_OBJ := $(subst .ino,_.cpp,$(patsubst %,$(BUILD_DIR)/%$(OBJ_EXT),$(notdir $(USER_SRC))))
USER_DIRS := $(sort $(dir $(USER_SRC)))
USER_INC_DIRS := $(sort $(dir $(USER_INC)))
# Use first flash definition for the board as default
FLASH_DEF ?= $(shell cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) {if (/^$(BOARD)\.menu\.FlashSize\.([^\.]+)=/){ print "$$1"; exit;}} print "NA";')
# The actual build commands are to be extracted from the Arduino description files
ARDUINO_MK = $(BUILD_DIR)/arduino.mk
ARDUINO_DESC := $(shell find $(ESP_ROOT) -maxdepth 1 -name "*.txt" | sort)
$(ARDUINO_MK): $(ARDUINO_DESC) $(MAKEFILE_LIST) | $(BUILD_DIR)
perl -e "$$PARSE_ARDUINO" $(BOARD) $(FLASH_DEF) $(ARDUINO_EXTRA_DESC) $(ARDUINO_DESC) >$(ARDUINO_MK)
-include $(ARDUINO_MK)
# Compilation directories and path
INCLUDE_DIRS += $(CORE_DIR) $(ESP_ROOT)/variants/$(INCLUDE_VARIANT) $(BUILD_DIR)
C_INCLUDES := $(foreach dir,$(INCLUDE_DIRS) $(USER_INC_DIRS),-I$(dir))
VPATH += $(shell find $(CORE_DIR) -type d) $(USER_DIRS)
# Automatically generated build information data
# Makes the build date and git descriptions at the actual build event available as string constants in the program
BUILD_INFO_H = $(BUILD_DIR)/buildinfo.h
BUILD_INFO_CPP = $(BUILD_DIR)/buildinfo.c++
BUILD_INFO_OBJ = $(BUILD_INFO_CPP)$(OBJ_EXT)
$(BUILD_INFO_H): | $(BUILD_DIR)
echo "typedef struct { const char *date, *time, *src_version, *env_version;} _tBuildInfo; extern _tBuildInfo _BuildInfo;" >$@
# Build rules for the different source file types
$(BUILD_DIR)/%.cpp$(OBJ_EXT): %.cpp $(BUILD_INFO_H) $(ARDUINO_MK)
echo $(<F)
$(CPP_COM) $(CPP_EXTRA) $< -o $@
$(BUILD_DIR)/%_.cpp$(OBJ_EXT): %.ino $(BUILD_INFO_H) $(ARDUINO_MK)
echo $(<F)
$(CPP_COM) $(CPP_EXTRA) -x c++ -include $(CORE_DIR)/Arduino.h $< -o $@
$(BUILD_DIR)/%.c$(OBJ_EXT): %.c $(ARDUINO_MK)
echo $(<F)
$(C_COM) $(C_EXTRA) $< -o $@
$(BUILD_DIR)/%.S$(OBJ_EXT): %.S $(ARDUINO_MK)
echo $(<F)
$(S_COM) $(S_EXTRA) $< -o $@
$(CORE_LIB): $(CORE_OBJ)
echo Creating core archive
rm -f $@
$(AR_COM) $^
BUILD_DATE = $(call time_string,"%Y-%m-%d")
BUILD_TIME = $(call time_string,"%H:%M:%S")
SRC_GIT_VERSION := $(call git_description,$(dir $(SKETCH)))
$(MAIN_EXE): $(CORE_LIB) $(USER_OBJ)
echo Linking $(MAIN_EXE)
echo " Versions: $(SRC_GIT_VERSION), $(ESP_ARDUINO_VERSION)"
echo '#include <buildinfo.h>' >$(BUILD_INFO_CPP)
echo '_tBuildInfo _BuildInfo = {"$(BUILD_DATE)","$(BUILD_TIME)","$(SRC_GIT_VERSION)","$(ESP_ARDUINO_VERSION)"};' >>$(BUILD_INFO_CPP)
$(CPP_COM) $(BUILD_INFO_CPP) -o $(BUILD_INFO_OBJ)
$(LD_COM)
$(GEN_PART_COM)
$(ELF2BIN_COM)
$(SIZE_COM) | perl -e "$$MEM_USAGE" "$(MEM_FLASH)" "$(MEM_RAM)"
ifneq ($(FLASH_INFO),)
printf "Flash size: $(FLASH_INFO)\n\n"
endif
perl -e 'print "Build complete. Elapsed time: ", time()-$(START_TIME), " seconds\n\n"'
upload flash: all
$(UPLOAD_COM)
ota: all
$(OTA_TOOL) -i $(ESP_ADDR) -p $(ESP_PORT) -a $(ESP_PWD) -f $(MAIN_EXE)
http: all
$(HTTP_TOOL) --verbose -F image=@$(MAIN_EXE) --user $(HTTP_USR):$(HTTP_PWD) http://$(HTTP_ADDR)$(HTTP_URI)
echo "\n"
$(FS_IMAGE): $(wildcard $(FS_DIR)/*)
ifneq ($(CHIP),esp32)
echo Generating filesystem image: $(FS_IMAGE)
$(MKSPIFFS_COM)
else
echo No SPIFFS function available for $(CHIP)
exit 1
endif
fs: $(FS_IMAGE)
upload_fs flash_fs: $(FS_IMAGE)
$(FS_UPLOAD_COM)
FLASH_FILE ?= esp_flash.bin
dump_flash:
echo Dumping flash memory to file: $(FLASH_FILE)
$(ESPTOOL_PY) read_flash 0 $(shell perl -e 'shift =~ /(\d+)([MK])/ || die "Invalid memory size\n";$$mem_size=$$1*1024;$$mem_size*=1024 if $$2 eq "M";print $$mem_size;' $(FLASH_DEF)) $(FLASH_FILE)
restore_flash:
echo Restoring flash memory from file: $(FLASH_FILE)
$(ESPTOOL_PY) write_flash -fs $(shell perl -e 'shift =~ /(\d+)([MK])/ || die "Invalid memory size\n";print ($$2 eq "K" ? 2 : $$1*8);' $(FLASH_DEF))m -fm $(FLASH_MODE) -ff $(FLASH_SPEED)m 0 $(FLASH_FILE)
clean:
echo Removing all build files
rm -rf $(BUILD_DIR)/*
list_boards:
echo === Available boards ===
cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) { if (/^(\w+)\.name=(.+)/){ print sprintf("%-20s %s\n", $$1,$$2);} }'
list_lib:
echo === User specific libraries ===
perl -e 'foreach (@ARGV) {print "$$_\n"}' "* Include directories:" $(USER_INC_DIRS) "* Library source files:" $(USER_SRC) "Foo" $(IGNORE_PATTERN)
list_flash_defs:
echo === Memory configurations for board: $(BOARD) ===
cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) { if (/^$(BOARD)\.menu\.FlashSize.([^\.]+)=(.+)/){ print sprintf("%-10s %s\n", $$1,$$2);} }'
help:
echo
echo "Generic makefile for building Arduino esp8266 and esp32 projects"
echo "This file can either be used directly or included from another makefile"
echo ""
echo "The following targets are available:"
echo " all (default) Build the project application"
echo " clean Remove all intermediate build files"
echo " flash Build and and flash the project application"
echo " flash_fs Build and and flash file system (when applicable)"
echo " ota Build and and flash via OTA"
echo " Params: ESP_ADDR, ESP_PORT and ESP_PWD"
echo " http Build and and flash via http (curl)"
echo " Params: HTTP_ADDR, HTTP_URI, HTTP_PWD and HTTP_USR"
echo " dump_flash Dump the whole board flash memory to a file"
echo " restore_flash Restore flash memory from a previously dumped file"
echo " list_lib Show a list of used library files and include paths"
echo "Configurable parameters:"
echo " SKETCH Main source file"
echo " If not specified the first sketch in current"
echo " directory will be used. If none is found there,"
echo " a demo example will be used instead."
echo " LIBS Includes in the sketch file of libraries from within"
echo " the ESP Arduino directories are automatically"
echo " detected. If this is not enough, define this"
echo " variable with all libraries or directories needed."
echo " USER_LIBS Path to user installed Arduino libraries"
echo " CHIP Set to esp8266 or esp32. Default: '$(CHIP)'"
echo " BOARD Name of the target board. Default: '$(BOARD)'"
echo " Use 'list_boards' to get list of available ones"
echo " FLASH_DEF Flash partitioning info. Default '$(FLASH_DEF)'"
echo " Use 'list_flash_defs' to get list of available ones"
echo " BUILD_DIR Directory for intermediate build files."
echo " Default '$(BUILD_DIR)'"
echo " BUILD_EXTRA_FLAGS Additional parameters for the compilation commands"
echo " FS_DIR File system root directory"
echo " UPLOAD_PORT Serial flashing port name. Default: '$(UPLOAD_PORT)'"
echo " UPLOAD_SPEED Serial flashing baud rate. Default: '$(UPLOAD_SPEED)'"
echo " FLASH_FILE File name for dump and restore flash operations"
echo " Default: '$(FLASH_FILE)'"
echo " VERBOSE Set to 1 to get full printout of the build"
echo " SINGLE_THREAD Use only one build thread"
echo
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
.PHONY: all
all: $(BUILD_DIR) $(ARDUINO_MK) $(BUILD_INFO_H) prebuild $(MAIN_EXE)
prebuild:
ifdef USE_PREBUILD
$(PREBUILD_COM)
endif
# Include all available dependencies
-include $(wildcard $(BUILD_DIR)/*$(DEP_EXT))
.DEFAULT_GOAL = all
ifndef SINGLE_THREAD
# Use multithreaded builds by default
MAKEFLAGS += -j
endif
ifndef VERBOSE
# Set silent mode as default
MAKEFLAGS += --silent
endif
# Inline Perl scripts
# Parse Arduino definitions and build commands from the descriptions
define PARSE_ARDUINO
my $$board = shift;
my $$flashSize = shift;
my %v;
sub def_var {
my ($$name, $$var) = @_;
print "$$var ?= $$v{$$name}\n";
$$v{$$name} = "\$$($$var)";
}
$$v{'runtime.platform.path'} = '$$(ESP_ROOT)';
$$v{'includes'} = '$$(C_INCLUDES)';
$$v{'runtime.ide.version'} = '10605';
$$v{'build.arch'} = '$$(CHIP)';
$$v{'build.project_name'} = '$$(MAIN_NAME)';
$$v{'build.path'} = '$$(BUILD_DIR)';
$$v{'object_files'} = '$$^ $$(BUILD_INFO_OBJ)';
foreach my $$fn (@ARGV) {
open($$f, $$fn) || die "Failed to open: $$fn\n";
while (<$$f>) {
next unless /^(\w[\w\-\.]+)=(.*)/;
my ($$key, $$val) =($$1, $$2);
$$board_defined = 1 if $$key eq "$$board.name";
$$key =~ s/$$board\.menu\.FlashSize\.$$flashSize\.//;
$$key =~ s/$$board\.menu\.FlashFreq\.[^\.]+\.//;
$$key =~ s/$$board\.menu\.UploadSpeed\.[^\.]+\.//;
$$key =~ s/^$$board\.//;
$$v{$$key} ||= $$val;
}
close($$f);
}
$$v{'runtime.tools.xtensa-lx106-elf-gcc.path'} ||= '$$(COMP_PATH)';
$$v{'runtime.tools.esptool.path'} ||= '$$(ESPTOOL_PATH)';
$$v{'runtime.tools.mkspiffs.path'} ||= '$$(MKSPIFFS_PATH)';
die "* Uknown board $$board\n" unless $$board_defined;
print "# Board definitions\n";
def_var('build.f_cpu', 'F_CPU');
def_var('build.flash_mode', 'FLASH_MODE');
def_var('build.flash_freq', 'FLASH_SPEED');
def_var('upload.resetmethod', 'UPLOAD_RESET');
def_var('upload.speed', 'UPLOAD_SPEED');
def_var('compiler.warning_flags', 'COMP_WARNINGS');
$$v{'upload.verbose'} = '$$(UPLOAD_VERB)';
$$v{'serial.port'} = '$$(UPLOAD_PORT)';
$$v{'recipe.objcopy.hex.pattern'} =~ s/[^"]+\/bootloaders\/eboot\/eboot.elf/\$$(BOOT_LOADER)/;
$$v{'tools.esptool.upload.pattern'} =~ s/\{(cmd|path)\}/\{tools.esptool.$$1\}/g;
$$v{'compiler.cpreprocessor.flags'} .= " \$$(C_PRE_PROC_FLAGS)";
$$v{'build.extra_flags'} .= " \$$(BUILD_EXTRA_FLAGS)";
foreach my $$key (sort keys %v) {
while ($$v{$$key} =~/\{/) {
$$v{$$key} =~ s/\{([\w\-\.]+)\}/$$v{$$1}/;
$$v{$$key} =~ s/""//;
}
$$v{$$key} =~ s/ -o $$//;
$$v{$$key} =~ s/(-D\w+=)"([^"]+)"/$$1\\"$$2\\"/g;
}
print "INCLUDE_VARIANT = $$v{'build.variant'}\n";
print "# Commands\n";
print "C_COM=$$v{'recipe.c.o.pattern'}\n";
print "CPP_COM=$$v{'recipe.cpp.o.pattern'}\n";
print "S_COM=$$v{'recipe.S.o.pattern'}\n";
print "AR_COM=$$v{'recipe.ar.pattern'}\n";
print "LD_COM=$$v{'recipe.c.combine.pattern'}\n";
print "GEN_PART_COM=$$v{'recipe.objcopy.eep.pattern'}\n";
print "ELF2BIN_COM=$$v{'recipe.objcopy.hex.pattern'}\n";
print "SIZE_COM=$$v{'recipe.size.pattern'}\n";
my $$flash_size = sprintf("0x%X", hex($$v{'build.spiffs_end'})-hex($$v{'build.spiffs_start'}));
print "MKSPIFFS_COM=$$v{'tools.mkspiffs.path'}/$$v{'tools.mkspiffs.cmd'} -b $$v{'build.spiffs_blocksize'} -s $$flash_size -c \$$(FS_DIR) \$$(FS_IMAGE)\n";
print "UPLOAD_COM=$$v{'tools.esptool.upload.pattern'}\n";
my $$fs_upload_com = $$v{'tools.esptool.upload.pattern'};
$$fs_upload_com =~ s/(.+ -ca) .+/$$1 $$v{'build.spiffs_start'} -cf \$$(FS_IMAGE)/;
print "FS_UPLOAD_COM=$$fs_upload_com\n";
my $$val = $$v{'recipe.hooks.core.prebuild.1.pattern'};
$$val =~ s/bash -c "(.+)"/$$1/;
$$val =~ s/(#define .+0x)(\`)/"\\$$1\"$$2/;
$$val =~ s/(\\)//;
print "PREBUILD_COM=$$val\n";
print "MEM_FLASH=$$v{'recipe.size.regex'}\n";
print "MEM_RAM=$$v{'recipe.size.regex.data'}\n";
print "FLASH_INFO=$$v{'menu.FlashSize.' . $$flashSize}\n"
endef
export PARSE_ARDUINO
# Convert memory information
define MEM_USAGE
$$fp = shift;
$$rp = shift;
while (<>) {
$$r += $$1 if /$$rp/;
$$f += $$1 if /$$fp/;
}
print "\nMemory usage\n";
print sprintf(" %-6s %6d bytes\n" x 2 ."\n", "Ram:", $$r, "Flash:", $$f);
endef
export MEM_USAGE

View file

@ -0,0 +1,34 @@
# ESP8266MeshIRRemote
This is an example of an IR Blaster controlled via MQTT commands
The blaster uses Pronto codes (though it should be easy to add support for all protocols handled by the IRRemote library).
The Pronto protocol is very flexible, and should be able to handle virtually all IR codes.
Codes can be saved in a file on the device to make it easy to send frequently used codes
## Hardware
The IRBlaster directory contains the Eagle libraries for the IRBlaster used in this example.
The board is quite basic. It uses an ESP01 module along with a 2n7000 to drive an IR LED. A LM1117-3.3 module is connected
to a mini-usb to provide power.
This was built before Eagle
was moved to a subscription plan. I have since moved to using KiCad, but there was no reason to redesign the schematics.
A PDF of the schematic is provided. Boards can be ordered from OshPark here:
<a href="https://oshpark.com/shared_projects/EaJlztYI"><img src="https://oshpark.com/assets/badge-5b7ec47045b78aef6eb9d83b3bac6b1920de805e9a0c227658eac6e19a045b9c.png" alt="Order from OSH Park"></img></a>
## MQTT Commands
| Topic | Message | Description |
|-------|---------|-------------|
| \<topic>/send | code=\<pronto code> | send specified code one time |
| \<topic>/send | repeat=5,code=\<pronto code> | send specified code 5 times |
| \<topic>/send | repeat=5,code=\<pronto code1>,repeat=3,pronto=\<pronto code2> | send code1 5 times followed by sending code2 3 times |
| \<topic>/send | repeat=5,file=\<filename1>,file=\<filename2>,... | send pronto code previously saved in 'filename1' 5 times, followed by the contents of 'filename2' |
| \<topic>/list | "" | returns a list of all saved files |
| \<topic>/debug | \<1|0> | enable/disable debugging messages over MQTT |
| \<topic>/save/\<filename> | code=\<pronto code> | save specified pronto code to 'filename' on esp8266 device |
| \<topic>/read/\<filename> | "" | return contents of 'flename' via MQTT |

View file

@ -0,0 +1,4 @@
FLASH_DEF = 1M256
USER_LIBS = ${HOME}/Arduino/libraries/
CPP_EXTRA = -Wall
BUILD_EXTRA_FLAGS = "-DMQTT_MAX_PACKET_SIZE=1152"

View file

@ -0,0 +1,20 @@
## Contributors of this project
- [Mark Szabo](https://github.com/markszabo/) : IR sending on ESP8266
- [Sébastien Warin](https://github.com/sebastienwarin/) (http://sebastien.warin.fr) : IR receiving on ESP8266
## Contributors of the original project (https://github.com/shirriff/Arduino-IRremote/)
These are the active contributors of this project that you may contact if there is anything you need help with or if you have suggestions.
- [z3t0](https://github.com/z3t0) : Active Contributor and currently also the main contributor.
* Email: zetoslab@gmail.com
* Skype: polarised16
- [shirriff](https://github.com/shirriff) : Owner of repository and creator of library.
- [Informatic](https://github.com/Informatic) : Active contributor
- [fmeschia](https://github.com/fmeschia) : Active contributor
- [PaulStoffregen](https://github.com/paulstroffregen) : Active contributor
- [crash7](https://github.com/crash7) : Active contributor
- [Neco777](https://github.com/neco777) : Active contributor
Note: This list is being updated constantly so please let [z3t0](https://github.com/z3t0) know if you have been missed.

View file

@ -0,0 +1,160 @@
/***************************************************
* IRremote for ESP8266
*
* Based on the IRremote library for Arduino by Ken Shirriff
* Version 0.11 August, 2009
* Copyright 2009 Ken Shirriff
* For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html
*
* Edited by Mitra to add new controller SANYO
*
* Interrupt code based on NECIRrcv by Joe Knapp
* http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556
* Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/
*
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
* LG added by Darryl Smith (based on the JVC protocol)
* Whynter A/C ARC-110WD added by Francesco Meschia
*
* Updated by markszabo (https://github.com/markszabo/IRremoteESP8266) for sending IR code on ESP8266
* Updated by Sebastien Warin (http://sebastien.warin.fr) for receiving IR code on ESP8266
*
* GPL license, all text above must be included in any redistribution
****************************************************/
#ifndef IRremote_h
#define IRremote_h
// The following are compile-time library options.
// If you change them, recompile the library.
// If DEBUG is defined, a lot of debugging output will be printed during decoding.
// TEST must be defined for the IRtest unittests to work. It will make some
// methods virtual, which will be slightly slower, which is why it is optional.
//#define DEBUG
//#define TEST
enum decode_type_t {
NEC = 1,
SONY = 2,
RC5 = 3,
RC6 = 4,
DISH = 5,
SHARP = 6,
PANASONIC = 7,
JVC = 8,
SANYO = 9,
MITSUBISHI = 10,
SAMSUNG = 11,
LG = 12,
WHYNTER = 13,
AIWA_RC_T501 = 14,
UNKNOWN = -1
};
// Results returned from the decoder
class decode_results {
public:
int decode_type; // NEC, SONY, RC5, UNKNOWN
union { // This is used for decoding Panasonic and Sharp data
unsigned int panasonicAddress;
unsigned int sharpAddress;
};
unsigned long value; // Decoded value
int bits; // Number of bits in decoded value
volatile unsigned int *rawbuf; // Raw intervals in .5 us ticks
int rawlen; // Number of records in rawbuf.
};
// Values for decode_type
#define NEC 1
#define SONY 2
#define RC5 3
#define RC6 4
#define DISH 5
#define SHARP 6
#define PANASONIC 7
#define JVC 8
#define SANYO 9
#define MITSUBISHI 10
#define SAMSUNG 11
#define LG 12
#define WHYNTER 13
#define UNKNOWN -1
// Decoded value for NEC when a repeat code is received
#define REPEAT 0xffffffff
// main class for receiving IR
class IRrecv
{
public:
IRrecv(int recvpin);
int decode(decode_results *results);
void enableIRIn();
void disableIRIn();
void resume();
private:
// These are called by decode
int getRClevel(decode_results *results, int *offset, int *used, int t1);
long decodeNEC(decode_results *results);
long decodeSony(decode_results *results);
long decodeSanyo(decode_results *results);
long decodeMitsubishi(decode_results *results);
long decodeRC5(decode_results *results);
long decodeRC6(decode_results *results);
long decodePanasonic(decode_results *results);
long decodeLG(decode_results *results);
long decodeJVC(decode_results *results);
long decodeSAMSUNG(decode_results *results);
long decodeWhynter(decode_results *results);
long decodeHash(decode_results *results);
int compare(unsigned int oldval, unsigned int newval);
};
// Only used for testing; can remove virtual for shorter code
#ifdef TEST
#define VIRTUAL virtual
#else
#define VIRTUAL
#endif
class IRsend
{
public:
IRsend(int IRsendPin);
void begin();
void sendWhynter(unsigned long data, int nbits);
void sendNEC(unsigned long data, int nbits);
void sendLG(unsigned long data, int nbits);
void sendSony(unsigned long data, int nbits);
// Neither Sanyo nor Mitsubishi send is implemented yet
// void sendSanyo(unsigned long data, int nbits);
// void sendMitsubishi(unsigned long data, int nbits);
void sendRaw(unsigned int buf[], int len, int hz);
void sendRC5(unsigned long data, int nbits);
void sendRC6(unsigned long data, int nbits);
void sendDISH(unsigned long data, int nbits);
void sendSharp(unsigned int address, unsigned int command);
void sendSharpRaw(unsigned long data, int nbits);
void sendPanasonic(unsigned int address, unsigned long data);
void sendJVC(unsigned long data, int nbits, int repeat); // *Note instead of sending the REPEAT constant if you want the JVC repeat signal sent, send the original code value and change the repeat argument from 0 to 1. JVC protocol repeats by skipping the header NOT by sending a separate code value like NEC does.
void sendSAMSUNG(unsigned long data, int nbits);
void sendDenon (unsigned long data, int nbits);
bool sendPronto (const char* s, bool repeat, bool fallback);
void enableIROut(int khz);
VIRTUAL void mark(int usec);
VIRTUAL void space(int usec);
private:
int halfPeriodicTime;
int IRpin;
} ;
// Some useful constants
#define USECPERTICK 50 // microseconds per clock interrupt tick
#define RAWBUF 100 // Length of raw duration buffer
// Marks tend to be 100us too long, and spaces 100us too short
// when received due to sensor lag.
#define MARK_EXCESS 100
#endif

View file

@ -0,0 +1,198 @@
/***************************************************
* IRremote for ESP8266
*
* Based on the IRremote library for Arduino by Ken Shirriff
* Version 0.11 August, 2009
* Copyright 2009 Ken Shirriff
* For details, see http://arcfn.com/2009/08/multi-protocol-infrared-remote-library.html
*
* Modified by Paul Stoffregen <paul@pjrc.com> to support other boards and timers
*
* Interrupt code based on NECIRrcv by Joe Knapp
* http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1210243556
* Also influenced by http://zovirl.com/2008/11/12/building-a-universal-remote-with-an-arduino/
*
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
* Whynter A/C ARC-110WD added by Francesco Meschia
*
* 09/23/2015 : Samsung pulse parameters updated by Sebastien Warin to be compatible with EUxxD6200
*
* GPL license, all text above must be included in any redistribution
****************************************************/
#ifndef IRremoteint_h
#define IRremoteint_h
#if defined(ARDUINO) && ARDUINO >= 100
#include <Arduino.h>
#else
#include <WProgram.h>
#endif
// Pulse parms are *50-100 for the Mark and *50+100 for the space
// First MARK is the one after the long gap
// pulse parameters in usec
#define WHYNTER_HDR_MARK 2850
#define WHYNTER_HDR_SPACE 2850
#define WHYNTER_BIT_MARK 750
#define WHYNTER_ONE_MARK 750
#define WHYNTER_ONE_SPACE 2150
#define WHYNTER_ZERO_MARK 750
#define WHYNTER_ZERO_SPACE 750
#define NEC_HDR_MARK 9000
#define NEC_HDR_SPACE 4500
#define NEC_BIT_MARK 560
#define NEC_ONE_SPACE 1690
#define NEC_ZERO_SPACE 560
#define NEC_RPT_SPACE 2250
#define SONY_HDR_MARK 2400
#define SONY_HDR_SPACE 600
#define SONY_ONE_MARK 1200
#define SONY_ZERO_MARK 600
#define SONY_RPT_LENGTH 45000
#define SONY_DOUBLE_SPACE_USECS 500 // usually ssee 713 - not using ticks as get number wrapround
// SA 8650B
#define SANYO_HDR_MARK 3500 // seen range 3500
#define SANYO_HDR_SPACE 950 // seen 950
#define SANYO_ONE_MARK 2400 // seen 2400
#define SANYO_ZERO_MARK 700 // seen 700
#define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround
#define SANYO_RPT_LENGTH 45000
// Mitsubishi RM 75501
// 14200 7 41 7 42 7 42 7 17 7 17 7 18 7 41 7 18 7 17 7 17 7 18 7 41 8 17 7 17 7 18 7 17 7
// #define MITSUBISHI_HDR_MARK 250 // seen range 3500
#define MITSUBISHI_HDR_SPACE 350 // 7*50+100
#define MITSUBISHI_ONE_MARK 1950 // 41*50-100
#define MITSUBISHI_ZERO_MARK 750 // 17*50-100
// #define MITSUBISHI_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround
// #define MITSUBISHI_RPT_LENGTH 45000
#define RC5_T1 889
#define RC5_RPT_LENGTH 46000
#define RC6_HDR_MARK 2666
#define RC6_HDR_SPACE 889
#define RC6_T1 444
#define RC6_RPT_LENGTH 46000
#define SHARP_BIT_MARK 245
#define SHARP_ONE_SPACE 1805
#define SHARP_ZERO_SPACE 795
#define SHARP_GAP 600000
#define SHARP_TOGGLE_MASK 0x3FF
#define SHARP_RPT_SPACE 3000
#define DISH_HDR_MARK 400
#define DISH_HDR_SPACE 6100
#define DISH_BIT_MARK 400
#define DISH_ONE_SPACE 1700
#define DISH_ZERO_SPACE 2800
#define DISH_RPT_SPACE 6200
#define DISH_TOP_BIT 0x8000
#define PANASONIC_HDR_MARK 3502
#define PANASONIC_HDR_SPACE 1750
#define PANASONIC_BIT_MARK 502
#define PANASONIC_ONE_SPACE 1244
#define PANASONIC_ZERO_SPACE 400
#define JVC_HDR_MARK 8000
#define JVC_HDR_SPACE 4000
#define JVC_BIT_MARK 600
#define JVC_ONE_SPACE 1600
#define JVC_ZERO_SPACE 550
#define JVC_RPT_LENGTH 60000
#define LG_HDR_MARK 8000
#define LG_HDR_SPACE 4000
#define LG_BIT_MARK 600
#define LG_ONE_SPACE 1600
#define LG_ZERO_SPACE 550
#define LG_RPT_LENGTH 60000
/*
#define SAMSUNG_HDR_MARK 5000
#define SAMSUNG_HDR_SPACE 5000
#define SAMSUNG_BIT_MARK 560
#define SAMSUNG_ONE_SPACE 1600
#define SAMSUNG_ZERO_SPACE 560
#define SAMSUNG_RPT_SPACE 2250
*/
// Update by Sebastien Warin for my EU46D6200
#define SAMSUNG_HDR_MARK 4500
#define SAMSUNG_HDR_SPACE 4500
#define SAMSUNG_BIT_MARK 590
#define SAMSUNG_ONE_SPACE 1690
#define SAMSUNG_ZERO_SPACE 590
#define SAMSUNG_RPT_SPACE 2250
#define SHARP_BITS 15
#define DISH_BITS 16
#define DENON_BITS 14 // The number of bits in the command
#define DENON_HDR_MARK 300 // The length of the Header:Mark
#define DENON_HDR_SPACE 750 // The lenght of the Header:Space
#define DENON_BIT_MARK 300 // The length of a Bit:Mark
#define DENON_ONE_SPACE 1800 // The length of a Bit:Space for 1's
#define DENON_ZERO_SPACE 750 // The length of a Bit:Space for 0's
#define TOLERANCE 25 // percent tolerance in measurements
#define LTOL (1.0 - TOLERANCE/100.)
#define UTOL (1.0 + TOLERANCE/100.)
#define _GAP 5000 // Minimum map between transmissions
#define GAP_TICKS (_GAP/USECPERTICK)
#define TICKS_LOW(us) (int) (((us)*LTOL/USECPERTICK))
#define TICKS_HIGH(us) (int) (((us)*UTOL/USECPERTICK + 1))
// receiver states
#define STATE_IDLE 2
#define STATE_MARK 3
#define STATE_SPACE 4
#define STATE_STOP 5
#define ERR 0
#define DECODED 1
// information for the interrupt handler
typedef struct {
uint8_t recvpin; // pin for IR data from detector
uint8_t rcvstate; // state machine
unsigned int timer; // state timer, counts 50uS ticks.
unsigned int rawbuf[RAWBUF]; // raw data
uint8_t rawlen; // counter of entries in rawbuf
}
irparams_t;
// Defined in IRremote.cpp
extern volatile irparams_t irparams;
// IR detector output is active low
#define MARK 0
#define SPACE 1
#define TOPBIT 0x80000000
#define NEC_BITS 32
#define SONY_BITS 12
#define SANYO_BITS 12
#define MITSUBISHI_BITS 16
#define MIN_RC5_SAMPLES 11
#define MIN_RC6_SAMPLES 1
#define PANASONIC_BITS 48
#define JVC_BITS 16
#define LG_BITS 28
#define SAMSUNG_BITS 32
#define WHYNTER_BITS 32
#endif

View file

@ -0,0 +1,458 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.

View file

@ -0,0 +1,27 @@
# IRremote ESP8266 Library
This library enables you to **send and receive** infra-red signals on an ESP8266 using Arduino framework (https://github.com/esp8266/Arduino)
This library is based on Ken Shirriff's work (https://github.com/shirriff/Arduino-IRremote/)
[Mark Szabo](https://github.com/markszabo/IRremoteESP8266) has updated the IRsend class to work on ESP8266 and [Sebastien Warin](https://github.com/sebastienwarin/IRremoteESP8266) the receiving & decoding part (IRrecv class).
Seb's notes : I also changed the pulse parameters for Samsung, update the Panasonic and Samsung decoders and remove the SANYO decoders. The IR decoder was successfully tested with Panasonic and Samsung remote controls.
## Installation
1. Click "Download ZIP"
2. Extract the downloaded zip file
3. Rename the extracted folder to "IRremoteESP8266"
4. Move this folder to your libraries directory (under windows: C:\Users\YOURNAME\Documents\Arduino\libraries\)
5. Restart your Arduino ide
6. Check out the examples
## Contributing
If you want to contribute to this project:
- Report bugs and errors
- Ask for enhancements
- Create issues and pull requests
- Tell other people about this library
## Contributors
Check [here](Contributors.md)

View file

@ -0,0 +1,88 @@
/*
* IRremoteESP8266: IRServer - demonstrates sending IR codes controlled from a webserver
* An IR LED must be connected to ESP8266 pin 0.
* Version 0.1 June, 2015
*/
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>
#include <IRremoteESP8266.h>
const char* ssid = ".....";
const char* password = ".....";
MDNSResponder mdns;
ESP8266WebServer server(80);
IRsend irsend(0);
void handleRoot() {
server.send(200, "text/html", "<html><head> <title>ESP8266 Demo</title></head><body><h1>Hello from ESP8266, you can send NEC encoded IR signals from here!</h1><p><a href=\"ir?code=16769055\">Send 0xFFE01F</a></p><p><a href=\"ir?code=16429347\">Send 0xFAB123</a></p><p><a href=\"ir?code=16771222\">Send 0xFFE896</a></p></body></html>");
}
void handleIr(){
for (uint8_t i=0; i<server.args(); i++){
if(server.argName(i) == "code")
{
unsigned long code = server.arg(i).toInt();
irsend.sendNEC(code, 36);
}
}
handleRoot();
}
void handleNotFound(){
String message = "File Not Found\n\n";
message += "URI: ";
message += server.uri();
message += "\nMethod: ";
message += (server.method() == HTTP_GET)?"GET":"POST";
message += "\nArguments: ";
message += server.args();
message += "\n";
for (uint8_t i=0; i<server.args(); i++){
message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
}
server.send(404, "text/plain", message);
}
void setup(void){
irsend.begin();
Serial.begin(115200);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
if (mdns.begin("esp8266", WiFi.localIP())) {
Serial.println("MDNS responder started");
}
server.on("/", handleRoot);
server.on("/ir", handleIr);
server.on("/inline", [](){
server.send(200, "text/plain", "this works as well");
});
server.onNotFound(handleNotFound);
server.begin();
Serial.println("HTTP server started");
}
void loop(void){
server.handleClient();
}

View file

@ -0,0 +1,28 @@
/*
* IRremoteESP8266: IRrecvDemo - demonstrates receiving IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 Sept, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
*/
#include <IRremoteESP8266.h>
int RECV_PIN = 2; //an IR detector/demodulatord is connected to GPIO pin 2
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
irrecv.resume(); // Receive the next value
}
delay(100);
}

View file

@ -0,0 +1,89 @@
/*
* IRremoteESP8266: IRrecvDump - dump details of IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 Sept, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
* LG added by Darryl Smith (based on the JVC protocol)
*/
#include <IRremoteESP8266.h>
int RECV_PIN = 2; //an IR detector/demodulatord is connected to GPIO pin 2
IRrecv irrecv(RECV_PIN);
decode_results results;
void setup()
{
Serial.begin(9600);
irrecv.enableIRIn(); // Start the receiver
}
void dump(decode_results *results) {
// Dumps out the decode_results structure.
// Call this after IRrecv::decode()
int count = results->rawlen;
if (results->decode_type == UNKNOWN) {
Serial.print("Unknown encoding: ");
}
else if (results->decode_type == NEC) {
Serial.print("Decoded NEC: ");
}
else if (results->decode_type == SONY) {
Serial.print("Decoded SONY: ");
}
else if (results->decode_type == RC5) {
Serial.print("Decoded RC5: ");
}
else if (results->decode_type == RC6) {
Serial.print("Decoded RC6: ");
}
else if (results->decode_type == PANASONIC) {
Serial.print("Decoded PANASONIC - Address: ");
Serial.print(results->panasonicAddress, HEX);
Serial.print(" Value: ");
}
else if (results->decode_type == LG) {
Serial.print("Decoded LG: ");
}
else if (results->decode_type == JVC) {
Serial.print("Decoded JVC: ");
}
else if (results->decode_type == AIWA_RC_T501) {
Serial.print("Decoded AIWA RC T501: ");
}
else if (results->decode_type == WHYNTER) {
Serial.print("Decoded Whynter: ");
}
Serial.print(results->value, HEX);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
Serial.print("Raw (");
Serial.print(count, DEC);
Serial.print("): ");
for (int i = 1; i < count; i++) {
if (i & 1) {
Serial.print(results->rawbuf[i]*USECPERTICK, DEC);
}
else {
Serial.write('-');
Serial.print((unsigned long) results->rawbuf[i]*USECPERTICK, DEC);
}
Serial.print(" ");
}
Serial.println();
}
void loop() {
if (irrecv.decode(&results)) {
Serial.println(results.value, HEX);
dump(&results);
irrecv.resume(); // Receive the next value
}
}

View file

@ -0,0 +1,169 @@
/*
* IRremoteESP8266: IRrecvDumpV2 - dump details of IR codes with IRrecv
* An IR detector/demodulator must be connected to the input RECV_PIN.
* Version 0.1 Sept, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
*/
#include <IRremoteESP8266.h>
int RECV_PIN = 2; //an IR detector/demodulator is connected to GPIO pin 2
IRrecv irrecv(RECV_PIN);
void setup ( )
{
Serial.begin(9600); // Status message will be sent to PC at 9600 baud
irrecv.enableIRIn(); // Start the receiver
}
//+=============================================================================
// Display IR code
//
void ircode (decode_results *results)
{
// Panasonic has an Address
if (results->decode_type == PANASONIC) {
Serial.print(results->panasonicAddress, HEX);
Serial.print(":");
}
// Print Code
Serial.print(results->value, HEX);
}
//+=============================================================================
// Display encoding type
//
void encoding (decode_results *results)
{
switch (results->decode_type) {
default:
case UNKNOWN: Serial.print("UNKNOWN"); break ;
case NEC: Serial.print("NEC"); break ;
case SONY: Serial.print("SONY"); break ;
case RC5: Serial.print("RC5"); break ;
case RC6: Serial.print("RC6"); break ;
case DISH: Serial.print("DISH"); break ;
case SHARP: Serial.print("SHARP"); break ;
case JVC: Serial.print("JVC"); break ;
case SANYO: Serial.print("SANYO"); break ;
case MITSUBISHI: Serial.print("MITSUBISHI"); break ;
case SAMSUNG: Serial.print("SAMSUNG"); break ;
case LG: Serial.print("LG"); break ;
case WHYNTER: Serial.print("WHYNTER"); break ;
case AIWA_RC_T501: Serial.print("AIWA_RC_T501"); break ;
case PANASONIC: Serial.print("PANASONIC"); break ;
}
}
//+=============================================================================
// Dump out the decode_results structure.
//
void dumpInfo (decode_results *results)
{
// Show Encoding standard
Serial.print("Encoding : ");
encoding(results);
Serial.println("");
// Show Code & length
Serial.print("Code : ");
ircode(results);
Serial.print(" (");
Serial.print(results->bits, DEC);
Serial.println(" bits)");
}
//+=============================================================================
// Dump out the decode_results structure.
//
void dumpRaw (decode_results *results)
{
// Print Raw data
Serial.print("Timing[");
Serial.print(results->rawlen-1, DEC);
Serial.println("]: ");
for (int i = 1; i < results->rawlen; i++) {
unsigned long x = results->rawbuf[i] * USECPERTICK;
if (!(i & 1)) { // even
Serial.print("-");
if (x < 1000) Serial.print(" ") ;
if (x < 100) Serial.print(" ") ;
Serial.print(x, DEC);
} else { // odd
Serial.print(" ");
Serial.print("+");
if (x < 1000) Serial.print(" ") ;
if (x < 100) Serial.print(" ") ;
Serial.print(x, DEC);
if (i < results->rawlen-1) Serial.print(", "); //',' not needed for last one
}
if (!(i % 8)) Serial.println("");
}
Serial.println(""); // Newline
}
//+=============================================================================
// Dump out the decode_results structure.
//
void dumpCode (decode_results *results)
{
// Start declaration
Serial.print("unsigned int "); // variable type
Serial.print("rawData["); // array name
Serial.print(results->rawlen - 1, DEC); // array size
Serial.print("] = {"); // Start declaration
// Dump data
for (int i = 1; i < results->rawlen; i++) {
Serial.print(results->rawbuf[i] * USECPERTICK, DEC);
if ( i < results->rawlen-1 ) Serial.print(","); // ',' not needed on last one
if (!(i & 1)) Serial.print(" ");
}
// End declaration
Serial.print("};"); //
// Comment
Serial.print(" // ");
encoding(results);
Serial.print(" ");
ircode(results);
// Newline
Serial.println("");
// Now dump "known" codes
if (results->decode_type != UNKNOWN) {
// Some protocols have an address
if (results->decode_type == PANASONIC) {
Serial.print("unsigned int addr = 0x");
Serial.print(results->panasonicAddress, HEX);
Serial.println(";");
}
// All protocols have data
Serial.print("unsigned int data = 0x");
Serial.print(results->value, HEX);
Serial.println(";");
}
}
//+=============================================================================
// The repeating section of the code
//
void loop ( )
{
decode_results results; // Somewhere to store the results
if (irrecv.decode(&results)) { // Grab an IR code
dumpInfo(&results); // Output the results
dumpRaw(&results); // Output the results in RAW format
dumpCode(&results); // Output the results as source code
Serial.println(""); // Blank line between entries
irrecv.resume(); // Prepare for the next value
}
}

View file

@ -0,0 +1,25 @@
/*
* IRremoteESP8266: IRsendDemo - demonstrates sending IR codes with IRsend
* An IR LED must be connected to ESP8266 pin 0.
* Version 0.1 June, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
*/
#include <IRremoteESP8266.h>
IRsend irsend(0); //an IR led is connected to GPIO pin 0
void setup()
{
irsend.begin();
Serial.begin(9600);
}
void loop() {
Serial.println("NEC");
irsend.sendNEC(0x00FFE01F, 36);
delay(2000);
Serial.println("Sony");
irsend.sendSony(0xa90, 12);
delay(2000);
}

View file

@ -0,0 +1,29 @@
/*
* IRremoteESP8266: IRsendDemo - demonstrates sending IR codes with IRsend
* An IR LED must be connected to ESP8266 pin 0.
* Version 0.1 June, 2015
* Based on Ken Shirriff's IrsendDemo Version 0.1 July, 2009, Copyright 2009 Ken Shirriff, http://arcfn.com
* JVC and Panasonic protocol added by Kristian Lauszus (Thanks to zenwheel and other people at the original blog post)
*/
#include <IRremoteESP8266.h>
#define PanasonicAddress 0x4004 // Panasonic address (Pre data)
#define PanasonicPower 0x100BCBD // Panasonic Power button
#define JVCPower 0xC5E8
IRsend irsend(0); //an IR led is connected to GPIO pin 0
void setup()
{
irsend.begin();
}
void loop() {
irsend.sendPanasonic(PanasonicAddress,PanasonicPower); // This should turn your TV on and off
irsend.sendJVC(JVCPower, 16,0); // hex value, 16 bits, no repeat
delayMicroseconds(50); // see http://www.sbprojects.com/knowledge/ir/jvc.php for information
irsend.sendJVC(JVCPower, 16,1); // hex value, 16 bits, repeat
delayMicroseconds(50);
}

View file

@ -0,0 +1,57 @@
#######################################
# Syntax Coloring Map For IRremote
#######################################
#######################################
# Datatypes (KEYWORD1)
#######################################
decode_results KEYWORD1
IRrecv KEYWORD1
IRsend KEYWORD1
#######################################
# Methods and Functions (KEYWORD2)
#######################################
decode KEYWORD2
enableIRIn KEYWORD2
disableIRIn KEYWORD2
resume KEYWORD2
begin KEYWORD2
enableIROut KEYWORD2
sendNEC KEYWORD2
sendSony KEYWORD2
sendSanyo KEYWORD2
sendMitsubishi KEYWORD2
sendRaw KEYWORD2
sendRC5 KEYWORD2
sendRC6 KEYWORD2
sendDISH KEYWORD2
sendSharp KEYWORD2
sendSharpRaw KEYWORD2
sendPanasonic KEYWORD2
sendJVC KEYWORD2
sendWhynter KEYWORD2
sendSAMSUNG KEYWORD2
#######################################
# Constants (LITERAL1)
#######################################
NEC LITERAL1
SONY LITERAL1
SANYO LITERAL1
MITSUBISHI LITERAL1
RC5 LITERAL1
RC6 LITERAL1
DISH LITERAL1
SHARP LITERAL1
PANASONIC LITERAL1
JVC LITERAL1
LG LITERAL1
SAMSUNG LITERAL1
WHYNTER LITERAL1
AIWA_RC_T501 LITERAL1
UNKNOWN LITERAL1
REPEAT LITERAL1

View file

@ -0,0 +1,12 @@
{
"name": "IRremoteESP8266",
"keywords": "infrared, ir, remote",
"description": "Send and receive infrared signals with multiple protocols",
"repository":
{
"type": "git",
"url": "https://github.com/sebastienwarin/IRremoteESP8266.git"
},
"frameworks": "arduino",
"platforms": "esp8266"
}

View file

@ -0,0 +1,9 @@
name=IRremoteESP8266
version=1.0.0
author=Sebastien Warin, Mark Szabo, Ken Shirriff
maintainer=Sebastien Warin
sentence=Send and receive infrared signals with multiple protocols.
paragraph=This library enables you to send and receive infra-red signals on an ESP8266.
category=Device Control
url=https://github.com/sebastienwarin/IRremoteESP8266
architectures=esp8266

View file

@ -0,0 +1,21 @@
#
# Example PlatformIO configuration file for SSL and non-SSL builds.
#
# Before you will be able to build the SSL version of this project, you will
# need to explicitly install the espressif8266_stage platform.
#
# To perform this installation, refer to step 1 of:
# http://docs.platformio.org/en/latest/platforms/espressif8266.html#using-arduino-framework-with-staging-version
[platformio]
env_default = nossl
[common]
framework = arduino
lib_deps = ESP8266MQTTMesh
[env:nossl]
platform = espressif8266
framework = arduino
board = esp01_1m
lib_deps = ${common.lib_deps}

View file

@ -0,0 +1,240 @@
/*
* Copyright (C) 2016 PhracturedBlue
*
* 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 <http://www.gnu.org/licenses/>.
*
* Based on IRremoteESP8266: IRServer - demonstrates sending IR codes controlled from a webserver
*
* esp8266IR Remote allows Pronto IR codes to be sent via an IR LED connected on GPIO2 via http
* It is recommended to drive an n-fet transistor connected to a resistor and diode, since the
* esp8266 can only supply 12mA on its GPIO pin.
*
* Known commands:
* NOTE: The maximum length of topic + payload is ~1156 bytes
* <topic>/send : code=<pronto code> : send specified code one time
* <topic>/send : repeat=5,code=<pronto code> : send specified code 5 times
* <topic>/send : repeat=5,code=<pronto code1>,repeat=3,pronto=<pronto code2> : send code1 5 times followed by sending code2 3 times
* <topic>/send : repeat=5,file=<filename> : send pronto code previously saved in 'filename' 5 times
* <topic>/list : "" : returns a list of all saved files
* <topic>/debug: <1|0> : enable/disable debugging messages over MQTT
* <topic>/save/<filename> : code=<pronto code> : save specified pronto code to 'filename' on esp8266 device
* <topic>/read/<filename> : "" : return contents of 'flename' via MQTT
*
* <topic> will generally be something like: 'esp8266-in/mesh_esp8266-7'
* Version 0.2 2017-04-16
*/
/* See credentials.h.examle for contents of credentials.h */
#include "credentials.h"
#include <ESP8266WiFi.h>
#include <FS.h>
#include <ESP8266MQTTMesh.h>
#include <IRremoteESP8266.h>
#include "QueueArray.h"
#define FIRMWARE_ID 0x2222
#define FIRMWARE_VER "0.2"
const wifi_conn networks[] = NETWORK_LIST;
const char* mqtt_server = MQTT_SERVER;
const char* mesh_password = MESH_PASSWORD;
ESP8266MQTTMesh mesh = ESP8266MQTTMesh::Builder(networks, mqtt_server)
.setVersion(FIRMWARE_VER, FIRMWARE_ID)
.setMeshPassword(mesh_password)
.build();
#define ESP8266_LED 2
bool debug = false;
class Cmd {
public:
Cmd(String _c, int _r, String _p, String _d = "") {
code = _c;
repeat = _r;
protocol = _p;
description = _d;
}
String code;
String protocol;
String description;
int repeat;
};
QueueArray<struct Cmd *> cmdQueue(10);
IRsend irsend(ESP8266_LED);
void handleList() {
String message = "{ \"Commands\": {";
Dir dir = SPIFFS.openDir("/ir/");
bool first = true;
while(dir.next()) {
if (! first) {
message += ",";
}
File f = dir.openFile("r");
int size = f.size();
f.close();
message += " \"" + dir.fileName().substring(4) + "\": " + String(size);
first = false;
}
FSInfo fs_info;
SPIFFS.info(fs_info);
message += " }, \"Free\": " + String(fs_info.totalBytes - fs_info.usedBytes) + "}";
mesh.publish("list", message.c_str());
}
Cmd *parse_code(const char *msg, bool queue = false) {
String code = "";
String protocol = "pronto";
int repeat = 0;
bool debug = false;
bool seen_repeat = false;
while (msg) {
char kv[1024];
char key[16];
const char *value;
ESP8266MQTTMesh::keyValue(msg, ',', kv, sizeof(kv), &msg);
if (! ESP8266MQTTMesh::keyValue(kv, '=', key, sizeof(key), &value)) {
continue;
};
if (0 == strcmp(key, "repeat")) {
repeat = atoi(value);
seen_repeat = true;
}
else if (0 == strcmp(key, "protocol")) {
protocol = value;
}
else if(0 == strcmp(key, "code")) {
code = value;
if (queue) {
cmdQueue.push(new Cmd(code, repeat, protocol, "Code len: " + String(code.length())));
}
}
else if(0 == strcmp(key, "file")) {
File f = SPIFFS.open("/ir/" + String(value), "r");
if (! f) {
Serial.println("Failed to read file: " + String(value));
continue;
}
protocol = f.readStringUntil('\n');
code = f.readStringUntil('\n');
String repeat_str = f.readStringUntil('\n');
if (repeat_str != "" && !seen_repeat) {
repeat = repeat_str.toInt();
}
if (queue) {
cmdQueue.push(new Cmd(code, repeat, protocol, "File: " + String(value)));
}
f.close();
}
}
if (queue) {
return NULL;
}
Cmd *cmd = new Cmd(code, repeat, protocol);
return cmd;
}
void callback(const char *topic, const char *msg)
{
char *endStr;
if (0 == strcmp(topic, "list")) {
handleList();
}
if (0 == strcmp(topic, "debug")) {
debug = atoi(msg);
}
else if (0 == strcmp(topic, "send")) {
parse_code(msg, true);
}
else if (strstr(topic, "read/") == topic) {
const char *filename = topic + 5;
File f = SPIFFS.open("/ir/" + String(filename), "r");
if (! f) {
Serial.println("Failed to read file: " + String(filename));
mesh.publish(topic, "{ \"Failed\": 1 }");
return;
}
String json = "{";
json += " \"protocol\": \"" + f.readStringUntil('\n') + "\"";
json += " \"code\": \"" + f.readStringUntil('\n') + "\"";
json += " \"repeat\": \"" + f.readStringUntil('\n') + "\"";
json += " }";
mesh.publish(topic, json.c_str());
}
else if (strstr(topic, "save/") == topic) {
const char *filename = topic + 5;
Cmd *cmd = parse_code(msg);
File f = SPIFFS.open("/ir/" + String(filename), "w");
if (! f) {
Serial.println("Failed to create file: " + String(filename));
mesh.publish(topic, "{ \"Failed\": 1 }");
} else {
f.print(cmd->protocol + "\n");
f.print(cmd->code + "\n");
f.print(String(cmd->repeat) + "\n");
f.close();
}
delete cmd;
}
}
void setup(void){
irsend.begin();
Serial.begin(115200);
mesh.setCallback(callback);
mesh.begin();
Serial.println("");
if (1) {
FSInfo fs_info;
SPIFFS.info(fs_info);
Serial.print("FS Used: ");
Serial.print(fs_info.usedBytes);
Serial.print(" Free: ");
Serial.print(fs_info.totalBytes - fs_info.usedBytes);
Serial.print(" Blocksize: ");
Serial.println(fs_info.blockSize);
Dir dir = SPIFFS.openDir("/ir/");
while(dir.next()) {
Serial.println("File: " + dir.fileName());
}
}
}
void loop(void){
if (! cmdQueue.isEmpty()) {
Cmd *nextCmd = cmdQueue.peek();
Serial.println("Sendng code: Repeat=" + String(nextCmd->repeat) + " queue size= " + cmdQueue.count());
if (debug) {
mesh.publish("tx", String("Queue Len: " + String(cmdQueue.count()) + " Repeat: " + String(nextCmd->repeat) + " Desc: " + nextCmd->description).c_str());
}
while (1) {
irsend.sendPronto(nextCmd->code.c_str(), nextCmd->repeat ? true : false, true);
if (nextCmd->repeat >= -1) {
break;
}
nextCmd->repeat++;
}
//irsend.sendPronto(nextCmd->code.c_str(), nextCmd->repeat ? true : false, true);
if (nextCmd->repeat <= 1) {
nextCmd = cmdQueue.pop();
delete nextCmd;
} else {
nextCmd->repeat--;
}
}
}

View file

@ -0,0 +1,242 @@
/*
* QueueArray.h
*
* Library implementing a generic, dynamic queue (array version).
*
* ---
*
* Copyright (C) 2010 Efstathios Chatzikyriakidis (contact@efxa.org)
*
* 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 <http://www.gnu.org/licenses/>.
*
* ---
*
* 2013-11-07 Marcus Nowotny <interactive-matter.eu>
* - pushing to a full array does not crash but returns false
*
* 2013-11-05 Marcus Nowotny <interactive-matter.eu>
* - rewritten to use a default size
* - texts are now in flash
*
* Version 1.0
*
* 2010-09-29 Efstathios Chatzikyriakidis <contact@efxa.org>
*
* - added resize(): for growing, shrinking the array size.
*
* 2010-09-25 Efstathios Chatzikyriakidis <contact@efxa.org>
*
* - added exit(), blink(): error reporting and handling methods.
*
* 2010-09-24 Alexander Brevig <alexanderbrevig@gmail.com>
*
* - added setPrinter(): indirectly reference a Serial object.
*
* 2010-09-20 Efstathios Chatzikyriakidis <contact@efxa.org>
*
* - initial release of the library.
*
* ---
*
* For the latest version see: http://www.arduino.cc/
*/
// header defining the interface of the source.
#ifndef _QUEUEARRAY_H
#define _QUEUEARRAY_H
// include Arduino basic header.
#include <Arduino.h>
// the definition of the queue class.
template<typename T>
class QueueArray {
public:
// init the queue (constructor).
QueueArray (const uint16_t initialSize);
// clear the queue (destructor).
~QueueArray ();
// push an item to the queue.
bool push (const T i);
// pop an item from the queue.
T pop ();
// get an item from the queue.
T peek () const;
// check if the queue is empty.
bool isEmpty () const;
// get the number of items in the queue.
uint16_t count () const;
// check if the queue is full.
bool isFull () const;
// set the printer of the queue.
void setStream (Stream & s);
private:
// exit report method in case of error.
void exit(const __FlashStringHelper*) const;
// led blinking method in case of error.
void blink () const;
Stream * stream; // the printer of the queue.
T * contents; // the array of the queue.
uint16_t size; // the size of the queue.
uint16_t items; // the number of items of the queue.
uint16_t head; // the head of the queue.
uint16_t tail; // the tail of the queue.
};
// init the queue (constructor).
template<typename T>
QueueArray<T>::QueueArray (const uint16_t initialSize) {
size = 0; // set the size of queue to zero.
items = 0; // set the number of items of queue to zero.
head = 0; // set the head of the queue to zero.
tail = 0; // set the tail of the queue to zero.
stream = NULL; // set the printer of queue to point nowhere.
// allocate enough memory for the array.
contents = (T *) malloc (sizeof (T) * initialSize);
// if there is a memory allocation error.
if (contents == NULL)
exit (F("QUEUE: insufficient memory to initialize queue."));
// set the initial size of the queue.
size = initialSize;
}
// clear the queue (destructor).
template<typename T>
QueueArray<T>::~QueueArray () {
free (contents); // deallocate the array of the queue.
contents = NULL; // set queue's array pointer to nowhere.
stream = NULL; // set the printer of queue to point nowhere.
size = 0; // set the size of queue to zero.
items = 0; // set the number of items of queue to zero.
head = 0; // set the head of the queue to zero.
tail = 0; // set the tail of the queue to zero.
}
// push an item to the queue.
template<typename T>
bool QueueArray<T>::push (const T i) {
// check if the queue is full.
if (isFull ())
// we cannot add anythif - just return false
return false;
// store the item to the array.
contents[tail++] = i;
// wrap-around index.
if (tail == size) tail = 0;
// increase the items.
items++;
//ok everything was fin
return true;
}
// pop an item from the queue.
template<typename T>
T QueueArray<T>::pop () {
// check if the queue is empty.
if (isEmpty ())
exit (F("QUEUE: can't pop item from queue: queue is empty."));
// fetch the item from the array.
T item = contents[head++];
// decrease the items.
items--;
// wrap-around index.
if (head == size) head = 0;
// return the item from the array.
return item;
}
// get an item from the queue.
template<typename T>
T QueueArray<T>::peek () const {
// check if the queue is empty.
if (isEmpty ())
exit (F("QUEUE: can't peek item from queue: queue is empty."));
// get the item from the array.
return contents[head];
}
// check if the queue is empty.
template<typename T>
bool QueueArray<T>::isEmpty () const {
return items == 0;
}
// check if the queue is full.
template<typename T>
bool QueueArray<T>::isFull () const {
return items == size;
}
// get the number of items in the queue.
template<typename T>
uint16_t QueueArray<T>::count () const {
return items;
}
// set the printer of the queue.
template<typename T>
void QueueArray<T>::setStream (Stream & s) {
stream = &s;
}
// exit report method in case of error.
template<typename T>
void QueueArray<T>::exit (const __FlashStringHelper * m) const {
// print the message if there is a printer.
if (stream)
stream->println (m);
// loop blinking until hardware reset.
blink ();
}
// led blinking method in case of error.
template<typename T>
void QueueArray<T>::blink () const {
while(1);
// solution selected due to lack of exit() and assert().
}
#endif // _QUEUEARRAY_H

View file

@ -0,0 +1,441 @@
#====================================================================================
# makeESPArduino
#
# A makefile for ESP8286 and ESP32 Arduino projects.
# Edit the contents of this file to suit your project
# or just include it and override the applicable macros.
#
# License: GPL 2.1
# General and full license information is available at:
# https://github.com/plerup/makeEspArduino
#
# Copyright (c) 2016-2017 Peter Lerup. All rights reserved.
#
#====================================================================================
#====================================================================================
# Project specfic values
#====================================================================================
# Include possible project makefile. This can be used to override the defaults below
-include $(firstword $(PROJ_CONF) $(dir $(SKETCH))config.mk)
#=== Default values not available in the Arduino configuration files
CHIP ?= esp8266
# Set chip specific default board unless specified
BOARD ?= $(if $(filter $(CHIP), esp32),esp32,generic)
# Serial flashing parameters
UPLOAD_PORT ?= $(shell ls -1tr /dev/ttyUSB* | tail -1)
UPLOAD_VERB ?= -v
# OTA parameters
ESP_ADDR ?= ESP_123456
ESP_PORT ?= 8266
ESP_PWD ?= 123
# HTTP update parameters
HTTP_ADDR ?= ESP_123456
HTTP_URI ?= /update
HTTP_PWD ?= user
HTTP_USR ?= password
# Output directory
BUILD_DIR ?= /tmp/mkESP/$(MAIN_NAME)_$(BOARD)
# File system source directory
FS_DIR ?= $(dir $(SKETCH))data
# Bootloader
BOOT_LOADER ?= $(ESP_ROOT)/bootloaders/eboot/eboot.elf
#====================================================================================
# Standard build logic and values
#====================================================================================
START_TIME := $(shell perl -e "print time();")
# Utility functions
git_description = $(shell git -C $(1) describe --tags --always --dirty 2>/dev/null || echo Unknown)
time_string = $(shell date +$(1))
# ESP Arduino directories
ifndef ESP_ROOT
# Location not defined, find and use possible version in the Arduino IDE installation
OS ?= $(shell uname -s)
ifeq ($(OS), Windows_NT)
ARDUINO_DIR = $(shell cygpath -m $(LOCALAPPDATA)/Arduino15/packages/$(CHIP))
else ifeq ($(OS), Darwin)
ARDUINO_DIR = $(HOME)/Library/Arduino15/packages/$(CHIP)
else
ARDUINO_DIR = $(HOME)/.arduino15/packages/$(CHIP)
endif
ESP_ROOT := $(lastword $(wildcard $(ARDUINO_DIR)/hardware/$(CHIP)/*))
ifeq ($(ESP_ROOT),)
$(error No installed version of $(CHIP) Arduino found)
endif
ESP_ARDUINO_VERSION := $(notdir $(ESP_ROOT))
# Find used version of compiler and tools
COMP_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/xtensa-lx106-elf-gcc/*))
ESPTOOL_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/esptool/*))
MKSPIFFS_PATH := $(lastword $(wildcard $(ARDUINO_DIR)/tools/mkspiffs/*))
else
# Location defined, assume it is a git clone
ESP_ARDUINO_VERSION = $(call git_description,$(ESP_ROOT))
endif
ESP_LIBS = $(ESP_ROOT)/libraries
SDK_ROOT = $(ESP_ROOT)/tools/sdk
TOOLS_ROOT = $(ESP_ROOT)/tools
ifeq ($(wildcard $(ESP_ROOT)/cores/$(CHIP)),)
$(error $(ESP_ROOT) is not a vaild directory for $(CHIP))
endif
ESPTOOL_PY = esptool.py --baud=$(UPLOAD_SPEED) --port $(UPLOAD_PORT)
# Search for sketch if not defined
SKETCH := $(realpath $(firstword \
$(SKETCH) \
$(wildcard *.ino) \
$(if $(filter $(CHIP), esp32),$(ESP_LIBS)/WiFi/examples/WiFiScan/WiFiScan.ino,$(ESP_LIBS)/ESP8266WebServer/examples/HelloServer/HelloServer.ino) \
) \
)
ifeq ($(wildcard $(SKETCH)),)
$(error Sketch $(SKETCH) not found)
endif
# Main output definitions
MAIN_NAME := $(basename $(notdir $(SKETCH)))
MAIN_EXE = $(BUILD_DIR)/$(MAIN_NAME).bin
FS_IMAGE = $(BUILD_DIR)/FS.spiffs
ifeq ($(OS), Windows_NT)
# Adjust critical paths
BUILD_DIR := $(shell cygpath -m $(BUILD_DIR))
SKETCH := $(shell cygpath -m $(SKETCH))
endif
# Build file extensions
OBJ_EXT = .o
DEP_EXT = .d
# Special tool definitions
OTA_TOOL ?= $(TOOLS_ROOT)/espota.py
HTTP_TOOL ?= curl
# Core source files
CORE_DIR = $(ESP_ROOT)/cores/$(CHIP)
CORE_SRC := $(shell find $(CORE_DIR) -name "*.S" -o -name "*.c" -o -name "*.cpp")
CORE_OBJ := $(patsubst %,$(BUILD_DIR)/%$(OBJ_EXT),$(notdir $(CORE_SRC)))
CORE_LIB = $(BUILD_DIR)/arduino.ar
# User defined compilation units and directories
ifeq ($(LIBS),)
# Automatically find directories with header files used by the sketch
FINDCMD := perl -e 'use File::Find;@d = split(" ", shift);while (<>) {$$f{"$$1"} = 1 if /^\s*\#include\s+[<"]([^>"]+)/;}find({follow => 1, wanted => sub {return if($$File::Find::dir =~ /examples|tests/);print $$File::Find::dir," " if $$f{$$_}}}, @d);'
LIBS := $(shell $(FINDCMD) "$(ESP_LIBS) $(HOME)/Arduino/libraries" $(SKETCH) ../../src/*.cpp ../../src/*.h)
ifeq ($(LIBS),)
# No dependencies found
LIBS = /dev/null
endif
endif
IGNORE_PATTERN := $(foreach dir,$(EXCLUDE_DIRS),$(dir)/%)
SKETCH_DIR = $(dir $(SKETCH))
USER_INC := $(filter-out $(IGNORE_PATTERN),$(shell find -L $(SKETCH_DIR) $(LIBS) -name "*.h"))
USER_SRC := $(SKETCH) $(filter-out $(IGNORE_PATTERN),$(shell find -L $(SKETCH_DIR) $(LIBS) -name "*.S" -o -name "*.c" -o -name "*.cpp"))
# Object file suffix seems to be significant for the linker...
USER_OBJ := $(subst .ino,_.cpp,$(patsubst %,$(BUILD_DIR)/%$(OBJ_EXT),$(notdir $(USER_SRC))))
USER_DIRS := $(sort $(dir $(USER_SRC)))
USER_INC_DIRS := $(sort $(dir $(USER_INC)))
# Use first flash definition for the board as default
FLASH_DEF ?= $(shell cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) {if (/^$(BOARD)\.menu\.FlashSize\.([^\.]+)=/){ print "$$1"; exit;}} print "NA";')
# The actual build commands are to be extracted from the Arduino description files
ARDUINO_MK = $(BUILD_DIR)/arduino.mk
ARDUINO_DESC := $(shell find $(ESP_ROOT) -maxdepth 1 -name "*.txt" | sort)
$(ARDUINO_MK): $(ARDUINO_DESC) $(MAKEFILE_LIST) | $(BUILD_DIR)
perl -e "$$PARSE_ARDUINO" $(BOARD) $(FLASH_DEF) $(ARDUINO_EXTRA_DESC) $(ARDUINO_DESC) >$(ARDUINO_MK)
-include $(ARDUINO_MK)
# Compilation directories and path
INCLUDE_DIRS += $(CORE_DIR) $(ESP_ROOT)/variants/$(INCLUDE_VARIANT) $(BUILD_DIR)
C_INCLUDES := $(foreach dir,$(INCLUDE_DIRS) $(USER_INC_DIRS),-I$(dir))
VPATH += $(shell find $(CORE_DIR) -type d) $(USER_DIRS)
# Automatically generated build information data
# Makes the build date and git descriptions at the actual build event available as string constants in the program
BUILD_INFO_H = $(BUILD_DIR)/buildinfo.h
BUILD_INFO_CPP = $(BUILD_DIR)/buildinfo.c++
BUILD_INFO_OBJ = $(BUILD_INFO_CPP)$(OBJ_EXT)
$(BUILD_INFO_H): | $(BUILD_DIR)
echo "typedef struct { const char *date, *time, *src_version, *env_version;} _tBuildInfo; extern _tBuildInfo _BuildInfo;" >$@
# Build rules for the different source file types
$(BUILD_DIR)/%.cpp$(OBJ_EXT): %.cpp $(BUILD_INFO_H) $(ARDUINO_MK)
echo $(<F)
$(CPP_COM) $(CPP_EXTRA) $< -o $@
$(BUILD_DIR)/%_.cpp$(OBJ_EXT): %.ino $(BUILD_INFO_H) $(ARDUINO_MK)
echo $(<F)
$(CPP_COM) $(CPP_EXTRA) -x c++ -include $(CORE_DIR)/Arduino.h $< -o $@
$(BUILD_DIR)/%.c$(OBJ_EXT): %.c $(ARDUINO_MK)
echo $(<F)
$(C_COM) $(C_EXTRA) $< -o $@
$(BUILD_DIR)/%.S$(OBJ_EXT): %.S $(ARDUINO_MK)
echo $(<F)
$(S_COM) $(S_EXTRA) $< -o $@
$(CORE_LIB): $(CORE_OBJ)
echo Creating core archive
rm -f $@
$(AR_COM) $^
BUILD_DATE = $(call time_string,"%Y-%m-%d")
BUILD_TIME = $(call time_string,"%H:%M:%S")
SRC_GIT_VERSION := $(call git_description,$(dir $(SKETCH)))
$(MAIN_EXE): $(CORE_LIB) $(USER_OBJ)
echo Linking $(MAIN_EXE)
echo " Versions: $(SRC_GIT_VERSION), $(ESP_ARDUINO_VERSION)"
echo '#include <buildinfo.h>' >$(BUILD_INFO_CPP)
echo '_tBuildInfo _BuildInfo = {"$(BUILD_DATE)","$(BUILD_TIME)","$(SRC_GIT_VERSION)","$(ESP_ARDUINO_VERSION)"};' >>$(BUILD_INFO_CPP)
$(CPP_COM) $(BUILD_INFO_CPP) -o $(BUILD_INFO_OBJ)
$(LD_COM)
$(GEN_PART_COM)
$(ELF2BIN_COM)
$(SIZE_COM) | perl -e "$$MEM_USAGE" "$(MEM_FLASH)" "$(MEM_RAM)"
ifneq ($(FLASH_INFO),)
printf "Flash size: $(FLASH_INFO)\n\n"
endif
perl -e 'print "Build complete. Elapsed time: ", time()-$(START_TIME), " seconds\n\n"'
upload flash: all
$(UPLOAD_COM)
ota: all
$(OTA_TOOL) -i $(ESP_ADDR) -p $(ESP_PORT) -a $(ESP_PWD) -f $(MAIN_EXE)
http: all
$(HTTP_TOOL) --verbose -F image=@$(MAIN_EXE) --user $(HTTP_USR):$(HTTP_PWD) http://$(HTTP_ADDR)$(HTTP_URI)
echo "\n"
$(FS_IMAGE): $(wildcard $(FS_DIR)/*)
ifneq ($(CHIP),esp32)
echo Generating filesystem image: $(FS_IMAGE)
$(MKSPIFFS_COM)
else
echo No SPIFFS function available for $(CHIP)
exit 1
endif
fs: $(FS_IMAGE)
upload_fs flash_fs: $(FS_IMAGE)
$(FS_UPLOAD_COM)
FLASH_FILE ?= esp_flash.bin
dump_flash:
echo Dumping flash memory to file: $(FLASH_FILE)
$(ESPTOOL_PY) read_flash 0 $(shell perl -e 'shift =~ /(\d+)([MK])/ || die "Invalid memory size\n";$$mem_size=$$1*1024;$$mem_size*=1024 if $$2 eq "M";print $$mem_size;' $(FLASH_DEF)) $(FLASH_FILE)
restore_flash:
echo Restoring flash memory from file: $(FLASH_FILE)
$(ESPTOOL_PY) write_flash -fs $(shell perl -e 'shift =~ /(\d+)([MK])/ || die "Invalid memory size\n";print ($$2 eq "K" ? 2 : $$1*8);' $(FLASH_DEF))m -fm $(FLASH_MODE) -ff $(FLASH_SPEED)m 0 $(FLASH_FILE)
clean:
echo Removing all build files
rm -rf $(BUILD_DIR)/*
list_boards:
echo === Available boards ===
cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) { if (/^(\w+)\.name=(.+)/){ print sprintf("%-20s %s\n", $$1,$$2);} }'
list_lib:
echo === User specific libraries ===
perl -e 'foreach (@ARGV) {print "$$_\n"}' "* Include directories:" $(USER_INC_DIRS) "* Library source files:" $(USER_SRC) "Foo" $(IGNORE_PATTERN)
list_flash_defs:
echo === Memory configurations for board: $(BOARD) ===
cat $(ESP_ROOT)/boards.txt | perl -e 'while (<>) { if (/^$(BOARD)\.menu\.FlashSize.([^\.]+)=(.+)/){ print sprintf("%-10s %s\n", $$1,$$2);} }'
help:
echo
echo "Generic makefile for building Arduino esp8266 and esp32 projects"
echo "This file can either be used directly or included from another makefile"
echo ""
echo "The following targets are available:"
echo " all (default) Build the project application"
echo " clean Remove all intermediate build files"
echo " flash Build and and flash the project application"
echo " flash_fs Build and and flash file system (when applicable)"
echo " ota Build and and flash via OTA"
echo " Params: ESP_ADDR, ESP_PORT and ESP_PWD"
echo " http Build and and flash via http (curl)"
echo " Params: HTTP_ADDR, HTTP_URI, HTTP_PWD and HTTP_USR"
echo " dump_flash Dump the whole board flash memory to a file"
echo " restore_flash Restore flash memory from a previously dumped file"
echo " list_lib Show a list of used library files and include paths"
echo "Configurable parameters:"
echo " SKETCH Main source file"
echo " If not specified the first sketch in current"
echo " directory will be used. If none is found there,"
echo " a demo example will be used instead."
echo " LIBS Includes in the sketch file of libraries from within"
echo " the ESP Arduino directories are automatically"
echo " detected. If this is not enough, define this"
echo " variable with all libraries or directories needed."
echo " USER_LIBS Path to user installed Arduino libraries"
echo " CHIP Set to esp8266 or esp32. Default: '$(CHIP)'"
echo " BOARD Name of the target board. Default: '$(BOARD)'"
echo " Use 'list_boards' to get list of available ones"
echo " FLASH_DEF Flash partitioning info. Default '$(FLASH_DEF)'"
echo " Use 'list_flash_defs' to get list of available ones"
echo " BUILD_DIR Directory for intermediate build files."
echo " Default '$(BUILD_DIR)'"
echo " BUILD_EXTRA_FLAGS Additional parameters for the compilation commands"
echo " FS_DIR File system root directory"
echo " UPLOAD_PORT Serial flashing port name. Default: '$(UPLOAD_PORT)'"
echo " UPLOAD_SPEED Serial flashing baud rate. Default: '$(UPLOAD_SPEED)'"
echo " FLASH_FILE File name for dump and restore flash operations"
echo " Default: '$(FLASH_FILE)'"
echo " VERBOSE Set to 1 to get full printout of the build"
echo " SINGLE_THREAD Use only one build thread"
echo
$(BUILD_DIR):
mkdir -p $(BUILD_DIR)
.PHONY: all
all: $(BUILD_DIR) $(ARDUINO_MK) $(BUILD_INFO_H) prebuild $(MAIN_EXE)
prebuild:
ifdef USE_PREBUILD
$(PREBUILD_COM)
endif
# Include all available dependencies
-include $(wildcard $(BUILD_DIR)/*$(DEP_EXT))
.DEFAULT_GOAL = all
ifndef SINGLE_THREAD
# Use multithreaded builds by default
MAKEFLAGS += -j
endif
ifndef VERBOSE
# Set silent mode as default
MAKEFLAGS += --silent
endif
# Inline Perl scripts
# Parse Arduino definitions and build commands from the descriptions
define PARSE_ARDUINO
my $$board = shift;
my $$flashSize = shift;
my %v;
sub def_var {
my ($$name, $$var) = @_;
print "$$var ?= $$v{$$name}\n";
$$v{$$name} = "\$$($$var)";
}
$$v{'runtime.platform.path'} = '$$(ESP_ROOT)';
$$v{'includes'} = '$$(C_INCLUDES)';
$$v{'runtime.ide.version'} = '10605';
$$v{'build.arch'} = '$$(CHIP)';
$$v{'build.project_name'} = '$$(MAIN_NAME)';
$$v{'build.path'} = '$$(BUILD_DIR)';
$$v{'object_files'} = '$$^ $$(BUILD_INFO_OBJ)';
foreach my $$fn (@ARGV) {
open($$f, $$fn) || die "Failed to open: $$fn\n";
while (<$$f>) {
next unless /^(\w[\w\-\.]+)=(.*)/;
my ($$key, $$val) =($$1, $$2);
$$board_defined = 1 if $$key eq "$$board.name";
$$key =~ s/$$board\.menu\.FlashSize\.$$flashSize\.//;
$$key =~ s/$$board\.menu\.FlashFreq\.[^\.]+\.//;
$$key =~ s/$$board\.menu\.UploadSpeed\.[^\.]+\.//;
$$key =~ s/^$$board\.//;
$$v{$$key} ||= $$val;
}
close($$f);
}
$$v{'runtime.tools.xtensa-lx106-elf-gcc.path'} ||= '$$(COMP_PATH)';
$$v{'runtime.tools.esptool.path'} ||= '$$(ESPTOOL_PATH)';
$$v{'runtime.tools.mkspiffs.path'} ||= '$$(MKSPIFFS_PATH)';
die "* Uknown board $$board\n" unless $$board_defined;
print "# Board definitions\n";
def_var('build.f_cpu', 'F_CPU');
def_var('build.flash_mode', 'FLASH_MODE');
def_var('build.flash_freq', 'FLASH_SPEED');
def_var('upload.resetmethod', 'UPLOAD_RESET');
def_var('upload.speed', 'UPLOAD_SPEED');
def_var('compiler.warning_flags', 'COMP_WARNINGS');
$$v{'upload.verbose'} = '$$(UPLOAD_VERB)';
$$v{'serial.port'} = '$$(UPLOAD_PORT)';
$$v{'recipe.objcopy.hex.pattern'} =~ s/[^"]+\/bootloaders\/eboot\/eboot.elf/\$$(BOOT_LOADER)/;
$$v{'tools.esptool.upload.pattern'} =~ s/\{(cmd|path)\}/\{tools.esptool.$$1\}/g;
$$v{'compiler.cpreprocessor.flags'} .= " \$$(C_PRE_PROC_FLAGS)";
$$v{'build.extra_flags'} .= " \$$(BUILD_EXTRA_FLAGS)";
foreach my $$key (sort keys %v) {
while ($$v{$$key} =~/\{/) {
$$v{$$key} =~ s/\{([\w\-\.]+)\}/$$v{$$1}/;
$$v{$$key} =~ s/""//;
}
$$v{$$key} =~ s/ -o $$//;
$$v{$$key} =~ s/(-D\w+=)"([^"]+)"/$$1\\"$$2\\"/g;
}
print "INCLUDE_VARIANT = $$v{'build.variant'}\n";
print "# Commands\n";
print "C_COM=$$v{'recipe.c.o.pattern'}\n";
print "CPP_COM=$$v{'recipe.cpp.o.pattern'}\n";
print "S_COM=$$v{'recipe.S.o.pattern'}\n";
print "AR_COM=$$v{'recipe.ar.pattern'}\n";
print "LD_COM=$$v{'recipe.c.combine.pattern'}\n";
print "GEN_PART_COM=$$v{'recipe.objcopy.eep.pattern'}\n";
print "ELF2BIN_COM=$$v{'recipe.objcopy.hex.pattern'}\n";
print "SIZE_COM=$$v{'recipe.size.pattern'}\n";
my $$flash_size = sprintf("0x%X", hex($$v{'build.spiffs_end'})-hex($$v{'build.spiffs_start'}));
print "MKSPIFFS_COM=$$v{'tools.mkspiffs.path'}/$$v{'tools.mkspiffs.cmd'} -b $$v{'build.spiffs_blocksize'} -s $$flash_size -c \$$(FS_DIR) \$$(FS_IMAGE)\n";
print "UPLOAD_COM=$$v{'tools.esptool.upload.pattern'}\n";
my $$fs_upload_com = $$v{'tools.esptool.upload.pattern'};
$$fs_upload_com =~ s/(.+ -ca) .+/$$1 $$v{'build.spiffs_start'} -cf \$$(FS_IMAGE)/;
print "FS_UPLOAD_COM=$$fs_upload_com\n";
my $$val = $$v{'recipe.hooks.core.prebuild.1.pattern'};
$$val =~ s/bash -c "(.+)"/$$1/;
$$val =~ s/(#define .+0x)(\`)/"\\$$1\"$$2/;
$$val =~ s/(\\)//;
print "PREBUILD_COM=$$val\n";
print "MEM_FLASH=$$v{'recipe.size.regex'}\n";
print "MEM_RAM=$$v{'recipe.size.regex.data'}\n";
print "FLASH_INFO=$$v{'menu.FlashSize.' . $$flashSize}\n"
endef
export PARSE_ARDUINO
# Convert memory information
define MEM_USAGE
$$fp = shift;
$$rp = shift;
while (<>) {
$$r += $$1 if /$$rp/;
$$f += $$1 if /$$fp/;
}
print "\nMemory usage\n";
print sprintf(" %-6s %6d bytes\n" x 2 ."\n", "Ram:", $$r, "Flash:", $$f);
endef
export MEM_USAGE

View file

@ -0,0 +1,27 @@
# ESP8266MeshSensor
This example is designed to use the ESP8266MQTTMesh library with a Sonoff Relay
(it has only been tested with the SonoffPOW, but should work with other variants
with minor changes)
## Required Libraries
The following libraries are required to build ths example
* ESP8266MQTTMesh
* HLW8012 (if using a Sonoff POW)
* OneWire (if using DS18B20)
* DallasTemperature (is using DS18B20)
## Compiling
The collowing configurations are needed before compiling:
* copy credentials.h.example to credentials.h and update as needed
* ensure the relevant pins are defined if you have a DS18B20 or HLW8012
## MQTT Commands
| Topic | Message | Description |
|---------------------|-------------|-------------|
| \<prefix>/heartbeat | \<number> | How often to send current status in millseconds (default 60000) |
| \<prefix>/expectedpower | \<number> | Calculate HLW8012 calibration based on current power |
| \<prefix>/expectedvoltage | \<number> | Calculate HLW8012 calibration based on current voltage |
| \<prefix>/expectedcurrent | \<number> | Calculate HLW8012 calibration based on current current |
| \<prefix>/resetpower | \<number> | Reset all of the HLW8012 calibration values |

View file

@ -0,0 +1,4 @@
FLASH_DEF = 2M
USER_LIBS = ${HOME}/Arduino/libraries/
CPP_EXTRA = -Wall
BUILD_EXTRA_FLAGS = "-DMQTT_MAX_PACKET_SIZE=1152"

View file

@ -0,0 +1,12 @@
#define NETWORK_LIST { \
"ssid 1", \
"ssid 2", \
"", \
}
#define NETWORK_PASSWORD "network password"
#define MESH_PASSWORD "esp8266_sensor_mesh"
#define BASE_SSID "mesh_esp8266-"
#define MQTT_SERVER "MQTT Server IP Address"
#define MQTT_PORT 1883
#define MESH_PORT 1884

View file

@ -0,0 +1,27 @@
#
# Example PlatformIO configuration file for SSL and non-SSL builds.
#
# Before you will be able to build the SSL version of this project, you will
# need to explicitly install the espressif8266_stage platform.
#
# To perform this installation, refer to step 1 of:
# http://docs.platformio.org/en/latest/platforms/espressif8266.html#using-arduino-framework-with-staging-version
[platformio]
env_default = nossl
[common]
framework = arduino
lib_deps = ESP8266MQTTMesh
lib_deps_external =
HLW8012
OneWire
DallasTemperature
[env:nossl]
platform = espressif8266@~1.6.0
framework = arduino
board = esp01_1m
lib_deps =
${common.lib_deps}
${common.lib_deps_external}

View file

@ -0,0 +1,393 @@
/*
* Copyright (C) 2016 PhracturedBlue
*
* 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 <http://www.gnu.org/licenses/>.
*
* HLW8012 code Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
*/
/* Sonoff POW w/ DS18B20 attached to GPIO2(SDA) */
#define GREEN_LED 15 //MTDO
#define RELAY 12 //MTDI
#define BUTTON 0 //GPIO0
#define DS18B20 2 //GPIO2
#define HLW8012_SEL 5 //GPIO5
#define HLW8012_CF 14 //MTMS
#define HLW8012_CF1 13 //MTCK
/* See credentials.h.examle for contents of credentials.h */
#include "credentials.h"
#include "capabilities.h"
#include <ESP8266WiFi.h>
#include <FS.h>
#if HAS_DS18B20
#include <OneWire.h>
#include <DallasTemperature.h>
#endif
#if HAS_HLW8012
#include <HLW8012.h>
#endif
#include <ESP8266MQTTMesh.h>
#if HAS_DS18B20 && HAS_HLW8012
#define FIRMWARE_ID 0x4455
#elif HAS_DS18B20
#define FIRMWARE_ID 0x4454
#elif HAS_HLW8012
#define FIRMWARE_ID 0x4453
#else
#define FIRMWARE_ID 0x4452
#endif
#define FIRMWARE_VER "0.8.1"
//const char* networks[] = NETWORK_LIST;
const wifi_conn networks[] = {
WIFI_CONN("foo", NETWORK_PASSWORD, NULL, false),
WIFI_CONN("bar", NETWORK_PASSWORD, "XX:XX:XX:XX:XX:XX", true),
NULL
};
const char* mesh_password = MESH_PASSWORD;
const char* mqtt_server = MQTT_SERVER;
#if HAS_DS18B20
OneWire oneWire(DS18B20);
DallasTemperature ds18b20(&oneWire);
DeviceAddress ds18b20Address;
#endif
#if HAS_HLW8012
#define HLW8012_CURRENT_R 0.001
#define HLW8012_VOLTAGE_R_UP ( 5 * 470000 ) // Real: 2280k
#define HLW8012_VOLTAGE_R_DOWN ( 1000 ) // Real 1.009k
#define HLW8012_UPDATE_INTERVAL 2000
#define HLW8012_MIN_CURRENT 0.05
#define HLW8012_MIN_POWER 10
HLW8012 hlw8012;
unsigned int power_sum;
unsigned int voltage_sum;
double current_sum;
double energy; //in Watt-Seconds
unsigned long power_sample_count = 0;
bool hlw8012Enabled = false;
void hlw8012_cf1_interrupt();
void hlw8012_cf_interrupt();
void hlw8012_enable_interrupts(bool enabled);
unsigned int hlw8012_getActivePower();
double hlw8012_getCurrent();
unsigned int hlw8012_getVoltage();
#endif
ESP8266MQTTMesh mesh = ESP8266MQTTMesh::Builder(networks, mqtt_server)
.setVersion(FIRMWARE_VER, FIRMWARE_ID)
.setMeshPassword(mesh_password)
.build();
bool relayState = false;
bool stateChanged = false;
int heartbeat = 60000;
float temperature = 0.0;
void read_config();
void save_config();
void callback(const char *topic, const char *msg);
String build_json();
void setup() {
pinMode(GREEN_LED, OUTPUT);
pinMode(RELAY, OUTPUT);
pinMode(BUTTON, INPUT);
Serial.begin(115200);
delay(5000);
mesh.setCallback(callback);
mesh.begin();
#if HAS_DS18B20
ds18b20.begin();
ds18b20.getAddress(ds18b20Address, 0);
ds18b20.setWaitForConversion(false);
ds18b20.requestTemperatures();
#endif
Serial.println("HLW8012 start");
#if HAS_HLW8012
hlw8012.begin(HLW8012_CF, HLW8012_CF1, HLW8012_SEL, HIGH, true);
hlw8012.setResistors(HLW8012_CURRENT_R, HLW8012_VOLTAGE_R_UP, HLW8012_VOLTAGE_R_DOWN);
#endif
Serial.println("HLW8012 end");
//mesh.setup will initialize the filesystem
if (SPIFFS.exists("/config")) {
read_config();
}
Serial.println("config end");
digitalWrite(RELAY, relayState);
}
void loop() {
static unsigned long pressed = 0;
static unsigned long lastSend = 0;
static bool needToSend = false;
unsigned long now = millis();
#if HAS_DS18B20
if (ds18b20.isConversionAvailable(ds18b20Address)) {
temperature = ds18b20.getTempF(ds18b20Address);
ds18b20.requestTemperatures();
}
#endif
#if HAS_HLW8012
if (! hlw8012Enabled && mesh.connected()) {
hlw8012_enable_interrupts(true);
} else if (hlw8012Enabled && ! mesh.connected()) {
hlw8012_enable_interrupts(false);
}
static unsigned long last_hlw8012_update = 0;
if (now - last_hlw8012_update > HLW8012_UPDATE_INTERVAL) {
static unsigned int power[3] = {0};
static unsigned int voltage[3] = {0};
static double current[3] = {0};
for (int i = 0; i < 2; i++) {
power[i] = power[i+1];
voltage[i] = voltage[i+1];
current[i] = current[i+1];
}
power[2] = hlw8012_getActivePower();
voltage[2] = hlw8012_getVoltage();
current[2] = hlw8012_getCurrent();
//Spike removal
if (power[1] > 0 && power[0] == 0 && power[2] == 0) {
power[1] = 0;
}
if (current[1] > 0 && current[0] == 0 && current[2] == 0) {
current[1] = 0;
}
if (voltage[1] > 0 && voltage[0] == 0 && voltage[2] == 0) {
voltage[1] = 0;
}
power_sum += power[0];
current_sum += current[0];
voltage_sum += voltage[0];
energy += 1.0 * power[0] * (now - last_hlw8012_update) / 1000.0;
power_sample_count++;
last_hlw8012_update = now;
}
#endif
if (! digitalRead(BUTTON)) {
if(pressed == 0) {
relayState = ! relayState;
digitalWrite(RELAY, relayState);
stateChanged = true;
}
pressed = now;
} else if (pressed && now - pressed > 100) {
pressed = 0;
}
if (stateChanged) {
save_config();
needToSend = true;
stateChanged = false;
} else if (now - lastSend > heartbeat) {
needToSend = true;
}
if (! mesh.connected()) {
return;
}
if (needToSend) {
lastSend = now;
String data = build_json();
#if HAS_HLW8012
power_sum = 0;
current_sum = 0;
voltage_sum = 0;
power_sample_count = 0;
#endif
mesh.publish("status", data.c_str());
needToSend = false;
}
}
void callback(const char *topic, const char *msg) {
if (0 == strcmp(topic, "heartbeat")) {
unsigned int hb = strtoul(msg, NULL, 10);
if (hb > 10000) {
heartbeat = hb;
save_config();
}
}
else if (0 == strcmp(topic, "state")) {
bool nextState = strtoul(msg, NULL, 10) ? true : false;
if (relayState != nextState) {
relayState = nextState;
digitalWrite(RELAY, relayState);
stateChanged = true;
}
}
#if HAS_HLW8012
else if (0 == strcmp(topic, "expectedpower")) {
int pow = atoi(msg);
if (pow > 0) {
hlw8012.expectedActivePower(pow);
save_config();
}
}
else if (0 == strcmp(topic, "expectedvoltage")) {
int volt = atoi(msg);
if (volt > 0) {
hlw8012.expectedVoltage(volt);
save_config();
}
}
else if (0 == strcmp(topic, "expectedcurrent")) {
double current = atof(msg);
if (current > 0) {
hlw8012.expectedCurrent(current);
save_config();
}
}
else if (0 == strcmp(topic, "resetpower")) {
int state = atoi(msg);
if (state > 0) {
hlw8012.resetMultipliers();
save_config();
}
}
#endif //HAS_HLW8012
}
String build_json() {
String msg = "{";
msg += " \"relay\":\"" + String(relayState ? "ON" : "OFF") + "\"";
#if HAS_DS18B20
msg += ", \"temp\":" + String(temperature, 2);
#endif
#if HAS_HLW8012
double count = power_sample_count ? power_sample_count : 1;
double power = (double)power_sum / count;
double current = (double)current_sum / count;
double voltage = (double)voltage_sum / count;
double apparent= voltage * current;
double pfactor = (apparent > 0) ? 100 * power / apparent : 100;
if (pfactor > 100) {
pfactor = 100;
}
msg += ", \"power\":" + String(power, 3);
msg += ", \"current\":" + String(current, 3);
msg += ", \"voltage\":" + String(voltage, 3);
msg += ", \"pf\":" + String(pfactor, 3);
msg += ", \"energy\":" + String(energy / 3600, 3); //Watt-Hours
#endif
msg += "}";
return msg;
}
void read_config() {
File f = SPIFFS.open("/config", "r");
if (! f) {
Serial.println("Failed to read config");
return;
}
while(f.available()) {
char s[32];
char key[32];
const char *value;
s[f.readBytesUntil('\n', s, sizeof(s)-1)] = 0;
if (! ESP8266MQTTMesh::keyValue(s, '=', key, sizeof(key), &value)) {
continue;
}
if (0 == strcmp(key, "RELAY")) {
relayState = value[0] == '0' ? 0 : 1;
}
else if (0 == strcmp(key, "HEARTBEAT")) {
heartbeat = atoi(value);
if (heartbeat < 1000) {
heartbeat = 1000;
} else if (heartbeat > 60 * 60 * 1000) {
heartbeat = 5 * 60 * 1000;
}
}
#if HAS_HLW8012
else if (0 == strcmp(key, "hlw8012PowerMult")) {
double dbl = atof(value);
if (dbl > 0) hlw8012.setPowerMultiplier(dbl);
}
else if (0 == strcmp(key, "hlw8012CurrentMult")) {
double dbl = atof(value);
if (dbl > 0) hlw8012.setCurrentMultiplier(dbl);
}
else if (0 == strcmp(key, "hlw8012VoltageMult")) {
double dbl = atof(value);
if (dbl > 0) hlw8012.setVoltageMultiplier(dbl);
}
#endif //HAS_HLW8012
}
f.close();
}
void save_config() {
File f = SPIFFS.open("/config", "w");
if (! f) {
Serial.println("Failed to write config");
return;
}
f.print("RELAY=" + String(relayState ? "1" : "0") + "\n");
f.print("HEARTBEAT=" + String(heartbeat) + "\n");
#if HAS_HLW8012
f.print("hlw8012PowerMult=" + String(hlw8012.getPowerMultiplier()));
f.print("hlw8012CurrentMult=" + String(hlw8012.getCurrentMultiplier()));
f.print("hlw8012VoltageMult=" + String(hlw8012.getVoltageMultiplier()));
#endif
f.close();
}
// When using interrupts we have to call the library entry point
// whenever an interrupt is triggered
#if HAS_HLW8012
void hlw8012_cf1_interrupt() {
hlw8012.cf1_interrupt();
}
void hlw8012_cf_interrupt() {
hlw8012.cf_interrupt();
}
void hlw8012_enable_interrupts(bool enabled) {
if (enabled) {
attachInterrupt(HLW8012_CF1, hlw8012_cf1_interrupt, CHANGE);
attachInterrupt(HLW8012_CF, hlw8012_cf_interrupt, CHANGE);
hlw8012Enabled = true;
} else {
detachInterrupt(HLW8012_CF1);
detachInterrupt(HLW8012_CF);
hlw8012Enabled = false;
}
}
unsigned int hlw8012_getActivePower() {
unsigned int power = hlw8012.getActivePower();
if (power < HLW8012_MIN_POWER) power = 0;
return power;
}
double hlw8012_getCurrent() {
double current = hlw8012.getCurrent();
if (current < HLW8012_MIN_CURRENT) current = 0;
return current;
}
unsigned int hlw8012_getVoltage() {
return hlw8012.getVoltage();
}
#endif

View file

@ -0,0 +1,15 @@
#ifndef _CAPABILITIES_H_
#define _CAPABILITIES_H_
#ifdef DS18B20
#define HAS_DS18B20 1
#else
#define HAS_DS18B20 0
#endif
#if defined(HLW8012_SEL) && defined(HLW8012_CF) && defined (HLW8012_CF1)
#define HAS_HLW8012 1
#else
#define HAS_HLW8012 0
#endif
#endif //_CAPABILITIES_H_

View file

@ -0,0 +1,43 @@
{
"name": "ESP8266MQTTMesh",
"keywords": "iot, home, automation, async, mqtt, client, esp8266, mesh, ota",
"description": "An Arduino for ESP8266 self-assembling Mesh network built around the MQTT protocol supporting OTA",
"version": "1.0.4",
"frameworks": "arduino",
"platforms": ["espressif8266", "espressif32"],
"authors":
{
"name": "PhracturedBlue",
"url": "https://github.com/PhracturedBlue"
},
"repository":
{
"type": "git",
"url": "https://github.com/PhracturedBlue/ESP8266MQTTMesh.git"
},
"dependencies": [
{
"name": "ESPAsyncTCP",
"version": "^1.1.3",
"platforms": "espressif8266"
},
{
"name": "AsyncMqttClient",
"version": "^0.8.1",
"platforms": "espressif8266"
},
{
"name": "AsyncTCP",
"platforms": "espressif32"
},
{
"name": "Ticker-esp32",
"platforms": "espressif32"
},
{
"name": "AsyncMqttClient",
"version": "https://github.com/marvinroger/async-mqtt-client#101277d",
"platforms": "espressif32"
}
]
}

View file

@ -0,0 +1,10 @@
name=ESP8266 MQTT Mesh
version=1.0.4
author=PhracturedBlue
maintainer=PhracturedBlue
sentence=Self-assembling Mesh network built around the MQTT protocol supporting OTA
paragraph=Self-assembling mesh network built around the MQTT protocol for the ESP8266 and ESP32 with OTA support
category=Communication
url=https://github.com/PhracturedBlue/ESP8266MQTTMesh
architectures=esp8266,esp32
includes=ESP8266MQTTMesh.h

View file

@ -0,0 +1,140 @@
/*Copyright (C) 2013 Adam Rudd
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 "Base64.h"
#include <pgmspace.h>
const char PROGMEM b64_alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
/* 'Private' declarations */
inline void a3_to_a4(unsigned char * a4, unsigned char * a3);
inline void a4_to_a3(unsigned char * a3, unsigned char * a4);
inline unsigned char b64_lookup(char c);
int base64_encode(char *output, const char *input, int inputLen) {
int i = 0, j = 0;
int encLen = 0;
unsigned char a3[3];
unsigned char a4[4];
while (inputLen--) {
a3[i++] = *(input++);
if (i == 3) {
a3_to_a4(a4, a3);
for (i = 0; i < 4; i++) {
output[encLen++] = pgm_read_byte(&b64_alphabet[a4[i]]);
}
i = 0;
}
}
if (i) {
for (j = i; j < 3; j++) {
a3[j] = '\0';
}
a3_to_a4(a4, a3);
for (j = 0; j < i + 1; j++) {
output[encLen++] = pgm_read_byte(&b64_alphabet[a4[j]]);
}
while ((i++ < 3)) {
output[encLen++] = '=';
}
}
output[encLen] = '\0';
return encLen;
}
int base64_decode(char * output, const char * input, int inputLen) {
int i = 0, j = 0;
int decLen = 0;
unsigned char a3[3];
unsigned char a4[4];
while (inputLen--) {
if (*input == '=') {
break;
}
a4[i++] = *(input++);
if (i == 4) {
for (i = 0; i < 4; i++) {
a4[i] = b64_lookup(a4[i]);
}
a4_to_a3(a3, a4);
for (i = 0; i < 3; i++) {
output[decLen++] = a3[i];
}
i = 0;
}
}
if (i) {
for (j = i; j < 4; j++) {
a4[j] = '\0';
}
for (j = 0; j < 4; j++) {
a4[j] = b64_lookup(a4[j]);
}
a4_to_a3(a3, a4);
for (j = 0; j < i - 1; j++) {
output[decLen++] = a3[j];
}
}
output[decLen] = '\0';
return decLen;
}
int base64_enc_len(int plainLen) {
int n = plainLen;
return (n + 2 - ((n + 2) % 3)) / 3 * 4;
}
int base64_dec_len(const char * input, int inputLen) {
int i = 0;
int numEq = 0;
for (i = inputLen - 1; input[i] == '='; i--) {
numEq++;
}
return ((6 * inputLen) / 8) - numEq;
}
inline void a3_to_a4(unsigned char * a4, unsigned char * a3) {
a4[0] = (a3[0] & 0xfc) >> 2;
a4[1] = ((a3[0] & 0x03) << 4) + ((a3[1] & 0xf0) >> 4);
a4[2] = ((a3[1] & 0x0f) << 2) + ((a3[2] & 0xc0) >> 6);
a4[3] = (a3[2] & 0x3f);
}
inline void a4_to_a3(unsigned char * a3, unsigned char * a4) {
a3[0] = (a4[0] << 2) + ((a4[1] & 0x30) >> 4);
a3[1] = ((a4[1] & 0xf) << 4) + ((a4[2] & 0x3c) >> 2);
a3[2] = ((a4[2] & 0x3) << 6) + a4[3];
}
inline unsigned char b64_lookup(char c) {
if (c >= 'A' && c <= 'Z') return c - 'A';
if (c >= 'a' && c <= 'z') return c - 71;
if (c >= '0' && c <= '9') return c + 4;
if (c == '+') return 62;
if (c == '/') return 63;
return -1;
}

View file

@ -0,0 +1,91 @@
/*
* Copyright (c) 2013 Adam Rudd.
* See LICENSE for more information
Copyright (C) 2013 Adam Rudd
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 _BASE64_H
#define _BASE64_H
/* b64_alphabet:
* Description: Base64 alphabet table, a mapping between integers
* and base64 digits
* Notes: This is an extern here but is defined in Base64.c
*/
extern const char b64_alphabet[];
/* base64_encode:
* Description:
* Encode a string of characters as base64
* Parameters:
* output: the output buffer for the encoding, stores the encoded string
* input: the input buffer for the encoding, stores the binary to be encoded
* inputLen: the length of the input buffer, in bytes
* Return value:
* Returns the length of the encoded string
* Requirements:
* 1. output must not be null or empty
* 2. input must not be null
* 3. inputLen must be greater than or equal to 0
*/
int base64_encode(char *output, const char *input, int inputLen);
/* base64_decode:
* Description:
* Decode a base64 encoded string into bytes
* Parameters:
* output: the output buffer for the decoding,
* stores the decoded binary
* input: the input buffer for the decoding,
* stores the base64 string to be decoded
* inputLen: the length of the input buffer, in bytes
* Return value:
* Returns the length of the decoded string
* Requirements:
* 1. output must not be null or empty
* 2. input must not be null
* 3. inputLen must be greater than or equal to 0
*/
int base64_decode(char *output, const char *input, int inputLen);
/* base64_enc_len:
* Description:
* Returns the length of a base64 encoded string whose decoded
* form is inputLen bytes long
* Parameters:
* inputLen: the length of the decoded string
* Return value:
* The length of a base64 encoded string whose decoded form
* is inputLen bytes long
* Requirements:
* None
*/
int base64_enc_len(int inputLen);
/* base64_dec_len:
* Description:
* Returns the length of the decoded form of a
* base64 encoded string
* Parameters:
* input: the base64 encoded string to be measured
* inputLen: the length of the base64 encoded string
* Return value:
* Returns the length of the decoded form of a
* base64 encoded string
* Requirements:
* 1. input must not be null
* 2. input must be greater than or equal to zero
*/
int base64_dec_len(const char *input, int inputLen);
#endif // _BASE64_H

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,252 @@
#ifndef _ESP8266MQTTMESH_H_
#define _ESP8266MQTTMESH_H_
#if ! defined(MQTT_MAX_PACKET_SIZE)
#define MQTT_MAX_PACKET_SIZE 1152
#endif
#if ! defined(ESP8266MESHMQTT_DISABLE_OTA) && ! defined(ESP32)
//By default we support OTA
#if ! defined(MQTT_MAX_PACKET_SIZE) || MQTT_MAX_PACKET_SIZE < (1024+128)
#error "Must define MQTT_MAX_PACKET_SIZE >= 1152"
#endif
#define HAS_OTA 1
#else
#define HAS_OTA 0
#endif
#include <Arduino.h>
#ifdef ESP32
#include <AsyncTCP.h>
#include <ESP32Ticker.h>
#define USE_WIFI_ONEVENT
#include "WiFiCompat.h"
#else
#include <ESP8266WiFi.h>
#include <ESPAsyncTCP.h>
#include <Ticker.h>
#endif
#include <AsyncMqttClient.h>
#include <FS.h>
#include <functional>
#ifdef ESP32
#define _chipID ((unsigned long)ESP.getEfuseMac())
#else
#define _chipID ESP.getChipId()
#endif
#define TOPIC_LEN 64
#define EMMDBG_EXTRA 0x10000000
#define EMMDBG_MSG 0x00000001
#define EMMDBG_MSG_EXTRA (EMMDBG_EXTRA | EMMDBG_MSG)
#define EMMDBG_WIFI 0x00000002
#define EMMDBG_WIFI_EXTRA (EMMDBG_EXTRA | EMMDBG_WIFI)
#define EMMDBG_MQTT 0x00000004
#define EMMDBG_MQTT_EXTRA (EMMDBG_EXTRA | EMMDBG_MQTT)
#define EMMDBG_OTA 0x00000008
#define EMMDBG_OTA_EXTRA (EMMDBG_EXTRA | EMMDBG_OTA)
#define EMMDBG_TIMING 0x00000010
#define EMMDBG_TIMING_EXTRA (EMMDBG_EXTRA | EMMDBG_TIMING)
#define EMMDBG_FS 0x00000020
#define EMMDBG_FS_EXTRA (EMMDBG_EXTRA | EMMDBG_OTA)
#define EMMDBG_ALL 0x8FFFFFFF
#define EMMDBG_ALL_EXTRA 0xFFFFFFFF
#define EMMDBG_NONE 0x00000000
#ifndef ESP8266_NUM_CLIENTS
#define ESP8266_NUM_CLIENTS 4
#endif
enum MSG_TYPE {
MSG_TYPE_NONE = 0xFE,
MSG_TYPE_INVALID = 0xFF,
MSG_TYPE_QOS_0 = 10,
MSG_TYPE_QOS_1 = 11,
MSG_TYPE_QOS_2 = 12,
MSG_TYPE_RETAIN_QOS_0 = 13,
MSG_TYPE_RETAIN_QOS_1 = 14,
MSG_TYPE_RETAIN_QOS_2 = 15,
};
typedef struct {
const uint8_t *cert;
const uint8_t *key;
const uint8_t *fingerprint;
uint32_t cert_len;
uint32_t key_len;
} ssl_cert_t;
typedef struct {
unsigned int len;
byte md5[16];
} ota_info_t;
typedef struct ap_t {
struct ap_t *next;
int32_t rssi;
uint8_t bssid[6];
int16_t ssid_idx;
} ap_t;
typedef struct {
const char *ssid;
const char *password;
const char *bssid;
bool hidden;
} wifi_conn;
#define WIFI_CONN(ssid, password, bssid, hidden) \
{ ssid, password, bssid, hidden }
class ESP8266MQTTMesh {
public:
class Builder;
private:
const unsigned int firmware_id;
const char *firmware_ver;
const wifi_conn *networks;
const char *mesh_ssid;
char mesh_password[64];
const char *mqtt_server;
const char *mqtt_username;
const char *mqtt_password;
const int mqtt_port;
const int mesh_port;
uint32_t mesh_bssid_key;
const char *inTopic;
const char *outTopic;
#if HAS_OTA
uint32_t freeSpaceStart;
uint32_t freeSpaceEnd;
uint32_t nextErase;
uint32_t startTime;
ota_info_t ota_info;
#endif
#if ASYNC_TCP_SSL_ENABLED
bool mqtt_secure;
ssl_cert_t mesh_secure;
const uint8_t *mqtt_fingerprint;
#endif
AsyncServer espServer;
AsyncClient *espClient[ESP8266_NUM_CLIENTS+1] = {0};
uint8_t espMAC[ESP8266_NUM_CLIENTS+1][6];
AsyncMqttClient mqttClient;
Ticker schedule;
int retry_connect;
ap_t *ap = NULL;
ap_t *ap_ptr;
ap_t *ap_unused = NULL;
char myID[10];
char inbuffer[ESP8266_NUM_CLIENTS+1][MQTT_MAX_PACKET_SIZE];
char *bufptr[ESP8266_NUM_CLIENTS+1];
long lastMsg = 0;
char msg[50];
int value = 0;
bool meshConnect = false;
unsigned long lastReconnect = 0;
unsigned long lastStatus = 0;
bool connecting = 0;
bool scanning = 0;
bool AP_ready = false;
std::function<void(const char *topic, const char *msg)> callback;
bool wifiConnected() { return (WiFi.status() == WL_CONNECTED); }
void die() { while(1) {} }
uint32_t lfsr(uint32_t seed, uint8_t b);
uint32_t encrypt_id(uint32_t id);
void generate_mac(uint8_t *bssid, uint32_t id);
bool verify_bssid(uint8_t *bssid);
int match_networks(const char *ssid, const char *bssid);
void scan();
void connect();
static void connect(ESP8266MQTTMesh *e) { e->connect(); };
String mac_str(uint8_t *bssid);
const char *build_mesh_ssid(char buf[32], uint8_t *mac);
void schedule_connect(float delay = 5.0);
void connect_mqtt();
void shutdown_AP();
void setup_AP();
void handle_client_data(int idx, char *data);
void parse_message(const char *topic, const char *msg);
void mqtt_callback(const char* topic, const byte* payload, unsigned int length);
uint16_t mqtt_publish(const char *topic, const char *msg, uint8_t msgType);
void publish(const char *topicDirection, const char *baseTopic, const char *subTopic, const char *msg, uint8_t msgType);
bool send_message(int index, const char *topicOrMsg, const char *msg = NULL, uint8_t msgType = MSG_TYPE_NONE);
void send_messages();
void send_connected_msg();
void broadcast_message(const char *topicOrMsg, const char *msg = NULL);
void get_fw_string(char *msg, int len, const char *prefix);
void handle_fw(const char *cmd);
void handle_ota(const char *cmd, const char *msg);
void parse_ota_info(const char *str);
char * md5(const uint8_t *msg, int len);
bool check_ota_md5();
void assign_subdomain();
static void assign_subdomain(ESP8266MQTTMesh *e) { e->assign_subdomain(); };
void erase_sector();
static void erase_sector(ESP8266MQTTMesh *e) { e->erase_sector(); };
void connectWiFiEvents();
#ifndef USE_WIFI_ONEVENT
WiFiEventHandler wifiConnectHandler;
WiFiEventHandler wifiDisconnectHandler;
WiFiEventHandler wifiAPConnectHandler;
WiFiEventHandler wifiAPDisconnectHandler;
#endif
void onWifiConnect(const WiFiEventStationModeGotIP& event);
void onWifiDisconnect(const WiFiEventStationModeDisconnected& event);
//void onDHCPTimeout();
void onAPConnect(const WiFiEventSoftAPModeStationConnected& ip);
void onAPDisconnect(const WiFiEventSoftAPModeStationDisconnected& ip);
void onMqttConnect(bool sessionPresent);
void onMqttDisconnect(AsyncMqttClientDisconnectReason reason);
void onMqttSubscribe(uint16_t packetId, uint8_t qos);
void onMqttUnsubscribe(uint16_t packetId);
void onMqttMessage(char* topic, char* payload, AsyncMqttClientMessageProperties properties, size_t len, size_t index, size_t total);
void onMqttPublish(uint16_t packetId);
int onSslFileRequest(const char *filename, uint8_t **buf);
void onClient(AsyncClient* c);
void onConnect(AsyncClient* c);
void onDisconnect(AsyncClient* c);
void onError(AsyncClient* c, int8_t error);
void onAck(AsyncClient* c, size_t len, uint32_t time);
void onTimeout(AsyncClient* c, uint32_t time);
void onData(AsyncClient* c, void* data, size_t len);
ESP8266MQTTMesh(const wifi_conn *networks,
const char *mqtt_server, int mqtt_port,
const char *mqtt_username, const char *mqtt_password,
const char *firmware_ver, int firmware_id,
const char *mesh_ssid, const char *mesh_password, int mesh_port,
#if ASYNC_TCP_SSL_ENABLED
bool mqtt_secure, const uint8_t *mqtt_fingerprint, ssl_cert_t mesh_secure,
#endif
const char *inTopic, const char *outTopic);
public:
void setCallback(std::function<void(const char *topic, const char *msg)> _callback);
void begin();
void publish(const char *subtopic, const char *msg, enum MSG_TYPE msgCmd = MSG_TYPE_NONE);
void publish_node(const char *subtopic, const char *msg, enum MSG_TYPE msgCmd = MSG_TYPE_NONE);
bool connected();
static bool keyValue(const char *data, char separator, char *key, int keylen, const char **value);
#ifdef USE_WIFI_ONEVENT
void WiFiEventHandler(system_event_id_t event, system_event_info_t info);
#endif
};
#include "ESP8266MQTTMeshBuilder.h"
#endif //_ESP8266MQTTMESH_H_

View file

@ -0,0 +1,142 @@
#ifndef _ESP8266MQTTMESHBUILDER_H_
#define _ESP8266MQTTMESHBUILDER_H_
class ESP8266MQTTMesh::Builder {
private:
const wifi_conn *networks;
const char *mqtt_server;
int mqtt_port;
const char *mqtt_username;
const char *mqtt_password;
const char *mesh_ssid;
const char *mesh_password;
int mesh_port;
const char *inTopic;
const char *outTopic;
unsigned int firmware_id;
const char *firmware_ver;
#if ASYNC_TCP_SSL_ENABLED
bool mqtt_secure;
ssl_cert_t mesh_secure;
const uint8_t *mqtt_fingerprint;
void fix_mqtt_port() { if (! mqtt_port) mqtt_port = mqtt_secure ? 8883 : 1883; };
#else
void fix_mqtt_port() { if (! mqtt_port) mqtt_port = 1883; };
#endif
public:
Builder(const wifi_conn *networks,
const char *mqtt_server,
int mqtt_port = 0):
networks(networks),
mqtt_server(mqtt_server),
mqtt_port(mqtt_port),
mqtt_username(NULL),
mqtt_password(NULL),
firmware_id(0),
firmware_ver(NULL),
mesh_ssid("esp8266_mqtt_mesh"),
mesh_password("ESP8266MQTTMesh"),
mesh_port(1884),
#if ASYNC_TCP_SSL_ENABLED
mqtt_secure(false),
mqtt_fingerprint(NULL),
mesh_secure({NULL, NULL, NULL, 0, 0}),
#endif
inTopic("esp8266-in/"),
outTopic("esp8266-out/")
{}
Builder& setVersion(const char *firmware_ver, int firmware_id) {
this->firmware_id = firmware_id;
this->firmware_ver = firmware_ver;
return *this;
}
Builder& setMqttAuth(const char *username, const char *password) {
this->mqtt_username = username;
this->mqtt_password = password;
return *this;
}
Builder& setMeshSSID(const char *ssid) { this->mesh_ssid = ssid; return *this; }
Builder& setMeshPassword(const char *password) { this->mesh_password = password; return *this; }
Builder& setMeshPort(int port) { this->mesh_port = port; return *this; }
Builder& setTopic(const char *inTopic, const char *outTopic) {
this->inTopic = inTopic;
this->outTopic = outTopic;
return *this;
}
#if ASYNC_TCP_SSL_ENABLED
Builder& setMqttSSL(bool enable, const uint8_t *fingerprint) {
this->mqtt_secure = enable;
this->mqtt_fingerprint = fingerprint;
return *this;
}
Builder & setMeshSSL(const uint8_t *ssl_cert, uint32_t ssl_cert_len,
const uint8_t *ssl_key, uint32_t ssl_key_len,
const uint8_t *ssl_fingerprint) {
this->mesh_secure.cert = ssl_cert;
this->mesh_secure.key = ssl_key;
this->mesh_secure.fingerprint = ssl_fingerprint;
this->mesh_secure.cert_len = ssl_cert_len;
this->mesh_secure.key_len = ssl_key_len;
return *this;
}
#endif
ESP8266MQTTMesh build() {
fix_mqtt_port();
return( ESP8266MQTTMesh(
networks,
mqtt_server,
mqtt_port,
mqtt_username,
mqtt_password,
firmware_ver,
firmware_id,
mesh_ssid,
mesh_password,
mesh_port,
#if ASYNC_TCP_SSL_ENABLED
mqtt_secure,
mqtt_fingerprint,
mesh_secure,
#endif
inTopic,
outTopic));
}
ESP8266MQTTMesh *buildptr() {
fix_mqtt_port();
return( new ESP8266MQTTMesh(
networks,
mqtt_server,
mqtt_port,
mqtt_username,
mqtt_password,
firmware_ver,
firmware_id,
mesh_ssid,
mesh_password,
mesh_port,
#if ASYNC_TCP_SSL_ENABLED
mqtt_secure,
mqtt_fingerprint,
mesh_secure,
#endif
inTopic,
outTopic));
}
};
#endif //_ESP8266MQTTMESHBUILDER_H_

View file

@ -0,0 +1,54 @@
/* This header file defines compatible structs that are not present in ESP32 */
#ifndef _WIFI_COMPAT_
#define _WIFI_COMPAT_
#include <WiFi.h>
typedef enum {
STATION_IF = 0, /**< ESP32 station interface */
SOFTAP_IF, /**< ESP32 soft-AP interface */
MAX_IF
} WIFI_INTERFACE;
static bool wifi_set_macaddr(WIFI_INTERFACE if_index, uint8_t *macaddr) {
if (if_index == SOFTAP_IF) {
int ok = esp_base_mac_addr_set(macaddr);
return ok == ESP_OK;
}
return true;
}
#define WIFI_DISCONNECT_REASON_ASSOC_TOOMANY WIFI_REASON_ASSOC_TOOMANY
struct WiFiEventStationModeGotIP
{
IPAddress ip;
IPAddress mask;
IPAddress gw;
};
struct WiFiEventStationModeDisconnected
{
String ssid;
uint8_t bssid[6];
unsigned int reason;
};
/*
struct WiFiEventSoftAPModeStationConnected
{
uint8_t mac[6];
uint8_t aid;
};
*/
#define WiFiEventSoftAPModeStationConnected system_event_ap_staconnected_t
/*
struct WiFiEventSoftAPModeStationDisconnected
{
uint8_t mac[6];
uint8_t aid;
};
*/
#define WiFiEventSoftAPModeStationDisconnected system_event_ap_stadisconnected_t
#endif //_WIFI_COMPAT_

View file

@ -0,0 +1,49 @@
#!/usr/bin/python
import subprocess
import sys
import re
import os
firmware = sys.argv[1]
stacktrace = sys.argv[2]
objdump = os.environ['HOME'] + "/.platformio/packages/toolchain-xtensa/bin/xtensa-lx106-elf-objdump"
dump = subprocess.check_output([objdump, '-S',firmware]).split('\n')
funcs = []
start = None
end = None
for line in dump:
#40208544 <_ZN15ESP8266MQTTMesh8setup_APEv>:
match = re.match(r'([0-9a-f]{8})\s+<(.*)>:', line)
if match:
funcs.append([int(match.group(1), 16), match.group(2)])
match = re.match(r'([0-9a-f]{8}):',line)
if match:
add = int(match.group(1), 16)
if not end or add > end:
end = add
if not start or add < start:
start = add
with open(stacktrace, "r") as fh:
in_stack = False
for line in fh:
if re.search(r'>>>stack>>>', line):
in_stack = True
if in_stack:
addrs = re.split(r'[: ]+', line)
for addr in addrs:
try:
add = int(addr, 16)
except:
continue
if add < start or add > end:
#print("Ignoring: %s (%08x, %08x)" % (addr, start, end))
continue
for i in range(0, len(funcs)):
if funcs[i][0] <= add:
continue
print("%s : %s" % (addr, funcs[i-1][1]))
break

View file

@ -0,0 +1,52 @@
#!/bin/bash
#This script is a slightly modified copy of:
#https://github.com/me-no-dev/ESPAsyncTCP/blob/master/ssl/gen_server_cert.sh
cat > ca_cert.conf << EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
O = Espressif Systems
EOF
openssl genrsa -out axTLS.ca_key.pem 2048
openssl req -new -config ./ca_cert.conf -key axTLS.ca_key.pem -out axTLS.ca_x509.req
openssl x509 -req -sha1 -days 5000 -signkey axTLS.ca_key.pem -CAkey axTLS.ca_key.pem -in axTLS.ca_x509.req -out axTLS.ca_x509.pem
cat > certs.conf << EOF
[ req ]
distinguished_name = req_distinguished_name
prompt = no
[ req_distinguished_name ]
O = axTLS on ESP8266
CN = esp8266.local
EOF
openssl genrsa -out axTLS.key_1024.pem 1024
openssl req -new -config ./certs.conf -key axTLS.key_1024.pem -out axTLS.x509_1024.req
openssl x509 -req -sha1 -CAcreateserial -days 5000 -CA axTLS.ca_x509.pem -CAkey axTLS.ca_key.pem -in axTLS.x509_1024.req -out axTLS.x509_1024.pem
openssl rsa -outform DER -in axTLS.key_1024.pem -out axTLS.key_1024
openssl x509 -outform DER -in axTLS.x509_1024.pem -out axTLS.x509_1024.cer
cat axTLS.key_1024 > server.key
cat axTLS.x509_1024.cer > server.cer
python -c 'import os; import hashlib; os.write(1,hashlib.sha1(open("server.cer", "rb").read()).digest())' > fingerprint
echo "const uint8_t ssl_key[] =" > ssl_cert.h
hexdump -v -e '16/1 "_x%02X" "\n"' server.key | sed 's/_/\\/g; s/\\x //g; s/.*/ "&"/' >> ssl_cert.h
echo ";" >> ssl_cert.h
echo "const uint32_t ssl_key_len = `cat server.key | wc -c`;" >> ssl_cert.h
echo "const uint8_t ssl_cert[] =" >> ssl_cert.h
hexdump -v -e '16/1 "_x%02X" "\n"' server.cer | sed 's/_/\\/g; s/\\x //g; s/.*/ "&"/' >> ssl_cert.h
echo ";" >> ssl_cert.h
echo "const uint32_t ssl_cert_len = `cat server.cer | wc -c`;" >> ssl_cert.h
echo "const uint8_t ssl_fingerprint[] =" >> ssl_cert.h
hexdump -v -e '16/1 "_x%02X" "\n"' fingerprint | sed 's/_/\\/g; s/\\x //g; s/.*/ "&"/' >> ssl_cert.h
echo ";" >> ssl_cert.h
rm axTLS.* ca_cert.conf certs.conf

View file

@ -0,0 +1,61 @@
#!/usr/bin/env python
# This script originally came from:
# https://github.com/marvinroger/async-mqtt-client/blob/master/scripts/get-fingerprint/get-fingerprint.py
import argparse
import ssl
import hashlib
import binascii
import sys
import socket
# The following came from https://tools.ietf.org/html/rfc5754#section-3
# This is crude, but works without requireing additional dependencies
signatures = {
"dsa_sha224": "30 0b 06 09 60 86 48 01 65 03 04 03 01",
"dsa_sha256": "30 0b 06 09 60 86 48 01 65 03 04 03 02",
"rsa_sha224": "30 0d 06 09 2a 86 48 86 f7 0d 01 01 0e 05 00",
"rsa_sha256": "30 0d 06 09 2a 86 48 86 f7 0d 01 01 0b 05 00",
"rsa_sha384": "30 0d 06 09 2a 86 48 86 f7 0d 01 01 0c 05 00",
"rsa_sha512": "30 0d 06 09 2a 86 48 86 f7 0d 01 01 0d 05 00",
"ecdsa_sha224": "30 0a 06 08 2a 86 48 ce 3d 04 03 01",
"ecdsa_sha256": "30 0a 06 08 2a 86 48 ce 3d 04 03 02",
"ecdsa_sha384": "30 0a 06 08 2a 86 48 ce 3d 04 03 03",
"ecdsa_sha512": "30 0a 06 08 2a 86 48 ce 3d 04 03 04"
}
parser = argparse.ArgumentParser(description='Compute SSL/TLS fingerprints.')
parser.add_argument('--host', required=True)
parser.add_argument('--port', default=8883)
args = parser.parse_args()
try:
cert_pem = ssl.get_server_certificate((args.host, args.port))
cert_der = ssl.PEM_cert_to_DER_cert(cert_pem)
except socket.error as e:
if str(e).find("[Errno 111]") is not -1:
print("ERROR: Could not connect to %s:%s" % (args.host, args.port))
elif str(e).find("[Errno 104]") is not -1:
print("ERROR: Mosquitto broker does not appear to be using TLS at %s:%s" % (args.host, args.port))
print(e)
sys.exit(1)
matches = []
for k in signatures:
fingerprint = binascii.a2b_hex(signatures[k].replace(" ", ""))
if cert_der.find(fingerprint) is not -1:
matches.append(k)
if not matches:
print("WARNING: Couldn't identify signature algorithm")
else:
print("INFO: Found signature algorithm: " + ", ".join(matches))
for sig in ("rsa_sha384", "rsa_sha512", "ecdsa_sha384", "ecdsa_sha512"):
if sig in matches:
print("ERROR: MQTT broker is using a %s signature which will not work with ESP8266" % (sig))
sha1 = hashlib.sha1(cert_der).hexdigest()
print("const uint8_t MQTT_FINGERPRINT[] = {0x" + ",0x".join([sha1[i:i+2] for i in range(0, len(sha1), 2)]) + "};")

View file

@ -0,0 +1,201 @@
#!/usr/bin/python3
import paho.mqtt.client as mqtt
import os
import sys
import argparse
import datetime
import hashlib
import base64
import time
import ssl
import re
import queue
topic = "esp8266-"
inTopic = topic + "in"
outTopic = topic + "out"
send_topic = ""
name=""
passw=""
q = queue.Queue();
def regex(pattern, txt, group):
group.clear()
match = re.search(pattern, txt)
if match:
if match.groupdict():
for k,v in match.groupdict().items():
group[k] = v
else:
group.extend(match.groups())
return True
return False
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
# Subscribing in on_connect() means that if we lose the connection and
# reconnect then subscriptions will be renewed.
client.subscribe("{}/#".format(outTopic))
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
#esp8266-out/mesh_esp8266-6/check=MD5 Passed
match = []
if regex(r'/([0-9a-f]+)/ota/erase$', msg.topic, match):
q.put(["erase", match[0]])
elif regex(r'([0-9a-f]+)/ota/md5/([0-9a-f]+)', msg.topic, match):
q.put(["md5", match[0], match[1], msg.payload])
elif regex(r'([0-9a-f]+)/ota/check$', msg.topic, match):
q.put(["check", match[0], msg.payload])
else:
#print("%s %-30s = %s" % (str(datetime.datetime.now()), msg.topic, str(msg.payload)));
pass
def wait_for(nodes, msgtype, maxTime, retries=0, pubcmd=None):
seen = {}
origTime = time.time()
startTime = origTime
while True:
try:
msg = q.get(True, 0.1)
if msg[0] == msgtype and (not nodes or msg[1] in nodes):
node = msg[1]
seen[node] = msg
else:
print("Got unexpected {} for node {}".format(msgtype, msg[1], msg))
except queue.Empty:
if time.time() - startTime < maxTime:
continue
if retries:
retries -= 1
print("{} node(s) missed the message, retrying".format(len(nodes) - len(seen.keys())))
client.publish(pubcmd[0], pubcmd[1])
startTime = time.time()
else:
print("{} node(s) missed the message and no retires left".format(len(nodes) - len(seen.keys())))
if nodes and len(seen.keys()) == len(nodes):
break
#print("Elapsed time waiting for {} messages: {} seconds".format(msgtype, time.time() - origTime))
return seen
def send_firmware(client, data, nodes):
md5 = base64.b64encode(hashlib.md5(data).digest())
payload = "md5:%s,len:%d" %(md5.decode(), len(data))
print("Erasing...")
client.publish("{}start".format(send_topic), payload)
nodes = list(wait_for(nodes, 'erase', 10).keys())
print("Updating firmware on the following nodes:\n\t{}".format("\n\t".join(nodes)))
pos = 0
while len(data):
d = data[0:768]
b64d = base64.b64encode(d)
data = data[768:]
client.publish("{}{}".format(send_topic, str(pos)), b64d)
expected_md5 = hashlib.md5(d).hexdigest().encode('utf-8')
seen = {}
retries = 1
seen = wait_for(nodes, 'md5', 1.0, 1, ["{}{}".format(send_topic, str(pos)), b64d])
for node in nodes:
if node not in seen:
print("No MD5 found for {} at 0x{}".format(node, pos))
return
addr = int(seen[node][2], 16)
md5 = seen[node][3]
if pos != addr:
print("Got unexpected address 0x{} (expected: 0x{}) from node {}".format(addr, pos, node))
return
if md5 != expected_md5:
print("Got unexpected md5 for node {} at 0x{}".format(node, addr))
print("\t {} (expected: {})".format(md5, expected_md5))
return
pos += len(d)
if pos % (768 * 13) == 0:
print("Transmitted %d bytes" % (pos))
print("Completed send")
client.publish("{}check".format(send_topic), "")
seen = wait_for(nodes, 'check', 5)
err = False
for node in nodes:
if node not in seen:
print("No verify result found for {}".format(node))
err = True
if seen[node][2] != b'MD5 Passed':
print("Node {} did not pass final MD5 check: {}".format(node, seen[node][2]))
err = True
if err:
return
print("Checksum verified. Flashing and rebooting now...")
client.publish("{}flash".format(send_topic), "")
def main():
global inTopic, outTopic, name, passw, send_topic
parser = argparse.ArgumentParser()
parser.add_argument("--bin", help="Input file");
parser.add_argument("--id", help="Firmware ID (n HEX)");
parser.add_argument("--broker", help="MQTT broker");
parser.add_argument("--port", help="MQTT broker port");
parser.add_argument("--user", help="MQTT broker user");
parser.add_argument("--password", help="MQTT broker password");
parser.add_argument("--ssl", help="MQTT broker SSL support");
parser.add_argument("--topic", help="MQTT mesh topic base (default: {}".format(topic))
parser.add_argument("--intopic", help="MQTT mesh in-topic (default: {}".format(inTopic))
parser.add_argument("--outtopic", help="MQTT mesh out-topic (default: {}".format(outTopic))
parser.add_argument("--node", help=("Specific node to send firmware to"))
args = parser.parse_args()
if not os.path.isfile(args.bin):
print("File: " + args.bin + " does not exist")
sys.exit(1)
if args.topic:
inTopic = args.topic + "in"
outTopic = args.topic + "out"
if args.intopic:
inTopic = args.intopic
if args.outtopic:
outTopic = args.outtopic
if args.id:
send_topic = "{}/ota/{}/".format(inTopic, args.id)
elif args.node:
send_topic = "{}/ota/{}/".format(inTopic, args.node)
else:
print("Must specify either --id or --node")
sys.exit(1)
print("File: {}".format(args.bin))
print("Sending to topic: {}".format(send_topic))
print("Listening to topic: {}".format(outTopic))
if not args.broker:
args.broker = "127.0.0.1"
if not args.port:
args.port = 1883
if args.user:
name = args.user
if args.password:
passw = args.password
client = mqtt.Client()
if args.ssl:
client.tls_set(ca_certs=None, certfile=None, keyfile=None, cert_reqs=ssl.CERT_REQUIRED,tls_version=ssl.PROTOCOL_TLS, ciphers=None)
if (args.user) or (args.password):
client.username_pw_set(name,passw)
client.on_connect = on_connect
client.on_message = on_message
client.connect(args.broker, args.port, 60)
client.loop_start()
fh = open(args.bin, "rb")
data = fh.read();
fh.close()
send_firmware(client, data, [args.node] if args.node else [])
client.loop_stop()
client.disconnect()
main()