70 Commits

Author SHA1 Message Date
c789056ccf Improve env var name
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2024-10-18 20:05:40 +02:00
f5f783698f Add support for environment files
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2024-10-18 19:57:06 +02:00
823783f307 Update ESP-IDF to version 5.3.1
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/tag Build is passing
2024-10-18 19:40:27 +02:00
187a8b3657 Merge branch 'master' of ssh://gitea.communiquons.org:52001/pierre/SolarEnergy
Some checks failed
continuous-integration/drone/push Build is failing
2024-10-18 18:17:28 +02:00
2c300109a3 Update Rust crate serde_json to v1.0.129
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-18 01:42:35 +00:00
6528de4a9e Update Rust crate libc to v0.2.161
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-10-18 00:28:57 +00:00
7846b093da Merge pull request 'Update Rust crate openssl-sys to v0.9.104' (#10) from renovate/openssl-sys-0.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #10
2024-10-17 06:44:32 +00:00
a2acbb53b0 Update Rust crate openssl-sys to v0.9.104
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2024-10-17 00:28:24 +00:00
9fd87b6452 Update Rust crate openssl to v0.10.68
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-10-17 00:28:19 +00:00
e151b50efa Update dependency @mui/icons-material to v6.1.4
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-10-16 00:28:18 +00:00
20abc120b5 Remove default README
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-15 22:49:33 +02:00
540d10bf78 Add README and start to work on build for prod guide
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-15 22:48:26 +02:00
f8bcb63513 Add license
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-15 22:29:26 +02:00
f920c4d9fa Merge pull request 'Update dependency vite to v5.4.9' (#6) from renovate/vite-5.x-lockfile into master
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #6
2024-10-15 20:28:18 +00:00
26bb6647b2 Update dependency vite to v5.4.9
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
2024-10-15 00:28:02 +00:00
8e1c2bc8bd Update Rust crate clap to v4.5.20
All checks were successful
continuous-integration/drone/pr Build is passing
continuous-integration/drone/push Build is passing
2024-10-15 00:27:54 +00:00
16b03f0a05 Add documentation to setup dev env
All checks were successful
continuous-integration/drone/push Build is passing
2024-10-14 23:07:06 +02:00
e1b5f2f282 Configure Renovate (#1)
All checks were successful
continuous-integration/drone/push Build is passing
Enable Renovate for the project
2024-10-14 20:43:29 +00:00
8a2ac0c434 Enable CI (#4)
All checks were successful
continuous-integration/drone/push Build is passing
Reviewed-on: #4
2024-10-14 20:42:20 +00:00
ebb4f8bdd2 Update dependencies 2024-10-14 22:14:55 +02:00
be77e7cb04 Upgraded ESP-IDF to version 5.3.1 2024-10-13 12:39:29 +02:00
13f8b5a592 Add support for legacy relays API 2024-10-12 20:53:23 +02:00
5408cd3a9c Can get consumption on Fronius inverter 2024-10-12 17:28:49 +02:00
784fe58c3e Display a message if no OTA update have been uploaded 2024-10-12 16:44:02 +02:00
5857892a4b Handle non-existent OTA storage directories 2024-10-12 16:42:01 +02:00
2f8b8aa59f Display a message if relays list is empty 2024-10-12 15:24:40 +02:00
e244fff700 Remove useless linebreaks in log messages 2024-10-12 17:02:39 +02:00
cbca7c8f4c OTA procedure is functional 2024-10-12 16:56:58 +02:00
521ccc899a Ready to implement OTA logic 2024-10-12 16:30:53 +02:00
a088ddc5b8 Determine firmware download URL 2024-10-12 16:10:07 +02:00
7e12e0df00 Update frontend dependencies 2024-10-12 15:51:03 +02:00
d90d033e74 Merge branch 'master' of http://10.0.0.10/pierre/SolarEnergy 2024-10-12 15:39:05 +02:00
e7190bab71 Make OTA update live 2024-10-09 18:46:51 +02:00
386f0439e4 Create the dialog to select the deployment target 2024-10-09 18:32:29 +02:00
e4da44b5ce Add a button to refresh the list of updates 2024-10-08 22:27:23 +02:00
138dd6c6b8 Minor improvments 2024-10-08 22:24:00 +02:00
eafa8e6a4b Can delete an OTA update 2024-10-08 22:22:57 +02:00
2e4a2b68dd Can manually download an OTA update 2024-10-08 22:13:36 +02:00
6cf7c2cae1 Display the list of OTA updates in the frontend 2024-10-08 21:53:21 +02:00
2924d14281 Firmware upload is functional 2024-10-07 22:13:47 +02:00
cef5b5aa5b Created form to upload new firmware 2024-10-07 22:04:57 +02:00
42f459f88b WIP OTA implementation 2024-10-05 20:39:05 +02:00
f4dda44d15 Prepare OTA execution 2024-10-05 20:28:55 +02:00
80452e10de Decode firmware update information 2024-10-05 20:13:36 +02:00
aa262879f0 Add route to download firmware on device 2024-10-05 20:00:57 +02:00
37844ae5fa Notify devices of available updates through sync endpoint 2024-10-05 19:44:32 +02:00
d38040cb98 Get the list of OTA updates for a given platform 2024-10-05 19:35:23 +02:00
2feb3f6490 Can set device desired version 2024-10-05 16:26:07 +02:00
2f971c0055 Add a route to upload update to the platform 2024-10-05 15:50:46 +02:00
e1a94acdcb Add a route to get the list of supported platforms for OTA 2024-10-05 13:03:30 +02:00
382c44a18a Let ESP IDF manage app version 2024-10-05 12:03:35 +02:00
17f8931f0f Enable logs reporting 2024-10-05 11:47:41 +02:00
cc63906ec1 Update frontend dependencies 2024-10-05 11:27:21 +02:00
59f8b59efe Merge branch 'master' of http://10.0.0.10/pierre/SolarEnergy 2024-10-05 11:11:23 +02:00
06659404c1 Prepare the path for OTA implementation 2024-10-03 21:16:51 +02:00
436bcd5677 Reverse display order of log messages 2024-10-03 21:01:38 +02:00
caf05d9126 Display log events 2024-10-03 20:52:05 +02:00
7dfb172aeb Frontend requests log on backend 2024-10-02 21:54:54 +02:00
75753051f9 Add function to extract logs 2024-10-01 22:27:34 +02:00
63bdeed952 Add function to report devices activity 2024-09-30 22:12:06 +02:00
7f952700ad Update sdkconfig for OTA 2024-09-29 18:33:41 +02:00
5608b4e610 Add ESP32 pinout 2024-09-28 21:14:09 +02:00
b4220a3254 Avoid bad relay trigger on startup 2024-09-28 20:33:11 +02:00
4d07d83904 Start to work on GPIOs 2024-09-28 20:27:12 +02:00
274b7089d1 Ready to implement GPIO logic to manage relays 2024-09-28 20:02:34 +02:00
e574bed96f Fix a memory leak 2024-09-28 16:42:10 +02:00
ce8427b0aa Handle fails more properly 2024-09-28 16:35:50 +02:00
58abf4ec9b Parse sync response from server 2024-09-28 16:35:05 +02:00
5704f2b57f Fix frontend images path 2024-09-28 11:40:29 +02:00
51fc7cc710 Update frontend dependencies 2024-09-28 11:32:43 +02:00
90 changed files with 4593 additions and 1166 deletions

70
.drone.yml Normal file
View File

@@ -0,0 +1,70 @@
---
kind: pipeline
type: docker
name: default
steps:
- name: web_build
image: node:21
volumes:
- name: web_app
path: /tmp/web_build
commands:
- cd central_frontend
- npm install
- npm run build
- mv dist /tmp/web_build
- name: backend_check
image: rust
volumes:
- name: rust_registry
path: /usr/local/cargo/registry
commands:
- rustup component add clippy
- cd central_backend
- cargo clippy -- -D warnings
- cargo test
- name: custom_consumption_check
image: rust
volumes:
- name: rust_registry
path: /usr/local/cargo/registry
commands:
- rustup component add clippy
- cd custom_consumption
- cargo clippy -- -D warnings
- cargo test
depends_on:
- backend_check
- name: backend_compile
image: rust
volumes:
- name: rust_registry
path: /usr/local/cargo/registry
- name: web_app
path: /tmp/web_build
depends_on:
- backend_check
- web_build
commands:
- cd central_backend
- mv /tmp/web_build/dist static
- cargo build --release
- ls -lah target/release/central_backend
- name: esp32_compile
image: espressif/idf:v5.3.1
commands:
- cd esp32_device
- /opt/esp/entrypoint.sh idf.py build
- ls -lah build/main.bin
volumes:
- name: rust_registry
temp: {}
- name: web_app
temp: {}

675
LICENSE Normal file
View File

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

View File

@@ -1,2 +1,18 @@
# SolarEnergy
WIP project
A project to optimize solar energy production and consumption. It connect to a current meter to decides whether some appliances controlled by relays shall be turned on or not, based on criterias such as:
* Minimal uptime
* Minimal downtime
* Daily minimal runtime
* Estimated consumption
* Dependencies, conflicts
## Components
* [`central_backend`](./central_backend): The core component that connects all the other one and make the decisions to turn on or off devices
* [`central_frontend`](./central_frontend): Web UI to configure the devices and monitor them
* [`custom_consumtion`](./custom_consumption): Development tool used to test different production values
* [`esp32_device`](./esp32_device/): The code installed in the MCU that controls relays (Wt32-Eth01 devices)
* [`python_device`](./python_device/): An alternative to the esp32 to control relays. Not production ready.
## Documentation
* [Setup for development](./docs/SETUP_DEV.md) guide
* [Setup for production](./docs/SETUP_PROD.md) guide

File diff suppressed because it is too large Load Diff

View File

@@ -7,26 +7,28 @@ edition = "2021"
log = "0.4.22"
env_logger = "0.11.5"
lazy_static = "1.5.0"
clap = { version = "4.5.18", features = ["derive", "env"] }
dotenvy = "0.15.7"
clap = { version = "4.5.20", features = ["derive", "env"] }
anyhow = "1.0.89"
thiserror = "1.0.63"
thiserror = "1.0.64"
openssl = { version = "0.10.66" }
openssl-sys = "0.9.102"
libc = "0.2.158"
libc = "0.2.159"
foreign-types-shared = "0.1.1"
asn1 = "0.17"
actix-web = { version = "4", features = ["openssl"] }
futures = "0.3.30"
futures = "0.3.31"
serde = { version = "1.0.210", features = ["derive"] }
reqwest = "0.12.7"
reqwest = { version = "0.12.7", features = ["json"] }
serde_json = "1.0.128"
rand = "0.8.5"
actix = "0.13.5"
actix-identity = "0.8.0"
actix-session = { version = "0.10.1", features = ["cookie-session"] }
actix-cors = "0.7.0"
actix-multipart = { version ="0.7.2", features = ["derive"] }
actix-remote-ip = "0.1.0"
futures-util = "0.3.30"
futures-util = "0.3.31"
uuid = { version = "1.10.0", features = ["v4", "serde"] }
semver = { version = "1.0.23", features = ["serde"] }
lazy-regex = "3.3.0"
@@ -39,3 +41,4 @@ prettytable-rs = "0.10.0"
chrono = "0.4.38"
serde_yml = "0.0.12"
bincode = "=2.0.0-rc.3"
fs4 = { version = "0.10.0", features = ["sync"] }

View File

@@ -1,4 +1,5 @@
use crate::devices::device::{DeviceId, DeviceRelayID};
use crate::ota::ota_update::OTAPlatform;
use clap::{Parser, Subcommand};
use std::path::{Path, PathBuf};
@@ -34,12 +35,23 @@ pub enum ConsumptionBackend {
#[clap(short, long, default_value = "/dev/shm/consumption.txt")]
path: String,
},
/// Fronius inverter consumption
Fronius {
/// The origin of the domain where the webserver of the Fronius Symo can be reached
#[clap(short, long, env = "FRONIUS_ORIG")]
origin: String,
},
}
/// Solar system central backend
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
pub struct AppConfig {
/// Read arguments from env file
#[clap(short, long, env)]
pub config: Option<String>,
/// Proxy IP, might end with a star "*"
#[clap(short, long, env)]
pub proxy_ip: Option<String>,
@@ -106,6 +118,21 @@ lazy_static::lazy_static! {
}
impl AppConfig {
/// Parse environment variables from file, if requedst
pub fn parse_env_file() -> anyhow::Result<()> {
if let Some(c) = Self::parse().config {
log::info!("Load additional environment variables from {c}");
let conf_file = Path::new(&c);
if !conf_file.is_file() {
panic!("Specified configuration is not a file!");
}
dotenvy::from_path(conf_file)?;
}
Ok(())
}
/// Get parsed command line arguments
pub fn get() -> &'static AppConfig {
&ARGS
@@ -283,6 +310,31 @@ impl AppConfig {
}
))
}
/// Get logs directory
pub fn logs_dir(&self) -> PathBuf {
self.storage_path().join("logs")
}
/// Get the logs for a given day
pub fn log_of_day(&self, day: u64) -> PathBuf {
self.logs_dir().join(format!("{day}.log"))
}
/// Get the directory that will store OTA updates
pub fn ota_dir(&self) -> PathBuf {
self.storage_path().join("ota")
}
/// Get the directory that will store OTA updates for a given platform
pub fn ota_platform_dir(&self, platform: OTAPlatform) -> PathBuf {
self.ota_dir().join(platform.to_string())
}
/// Get the path to the file that will contain an OTA update
pub fn path_ota_update(&self, platform: OTAPlatform, version: &semver::Version) -> PathBuf {
self.ota_platform_dir(platform).join(version.to_string())
}
}
#[cfg(test)]

View File

@@ -13,6 +13,9 @@ pub const MAX_INACTIVITY_DURATION: u64 = 3600;
/// Maximum session duration (1 day)
pub const MAX_SESSION_DURATION: u64 = 3600 * 24;
/// Maximum firmware size (in bytes)
pub const MAX_FIRMWARE_SIZE: usize = 50 * 1000 * 1000;
/// List of routes that do not require authentication
pub const ROUTES_WITHOUT_AUTH: [&str; 2] =
["/web_api/server/config", "/web_api/auth/password_auth"];

View File

@@ -9,9 +9,9 @@ use std::collections::{HashMap, HashSet};
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct DeviceInfo {
/// Device reference
reference: String,
pub reference: String,
/// Device firmware / software version
version: semver::Version,
pub version: semver::Version,
/// Maximum number of relay that the device can support
pub max_relays: usize,
}
@@ -62,6 +62,9 @@ pub struct Device {
///
/// There cannot be more than [info.max_relays] relays
pub relays: Vec<DeviceRelay>,
/// Desired version, ie. the version of the software we would to seen run on the device
#[serde(skip_serializing_if = "Option::is_none")]
pub desired_version: Option<semver::Version>,
}
/// Structure that contains information about the minimal expected execution

View File

@@ -84,6 +84,7 @@ impl DevicesList {
validated: false,
enabled: false,
relays: vec![],
desired_version: None,
};
// First, write CSR
@@ -186,6 +187,24 @@ impl DevicesList {
Ok(())
}
/// Set a device desired version
pub fn set_desired_version(
&mut self,
id: &DeviceId,
version: Option<semver::Version>,
) -> anyhow::Result<()> {
let dev = self
.0
.get_mut(id)
.ok_or(DevicesListError::UpdateDeviceFailedDeviceNotFound)?;
dev.desired_version = version;
self.persist_dev_config(id)?;
Ok(())
}
/// Get single certificate information
fn get_cert(&self, id: &DeviceId) -> anyhow::Result<X509> {
let dev = self

View File

@@ -13,6 +13,30 @@ pub enum ConsumptionError {
pub type EnergyConsumption = i32;
#[derive(serde::Deserialize)]
struct FroniusResponse {
#[serde(rename = "Body")]
body: FroniusResponseBody,
}
#[derive(serde::Deserialize)]
struct FroniusResponseBody {
#[serde(rename = "Data")]
data: FroniusResponseBodyData,
}
#[derive(serde::Deserialize)]
struct FroniusResponseBodyData {
#[serde(rename = "Site")]
site: FroniusResponseSite,
}
#[derive(serde::Deserialize)]
struct FroniusResponseSite {
#[serde(rename = "P_Grid")]
grid_production: f64,
}
/// Get current electrical energy consumption
pub async fn get_curr_consumption() -> anyhow::Result<EnergyConsumption> {
let backend = AppConfig::get()
@@ -38,5 +62,12 @@ pub async fn get_curr_consumption() -> anyhow::Result<EnergyConsumption> {
.parse()
.map_err(ConsumptionError::FileInvalidContent)?)
}
ConsumptionBackend::Fronius { origin } => {
let url = format!("{origin}/solar_api/v1/GetPowerFlowRealtimeData.fcgi");
let response = reqwest::get(url).await?.json::<FroniusResponse>().await?;
Ok(response.body.data.site.grid_production as i32)
}
}
}

View File

@@ -132,12 +132,14 @@ impl ConsumptionHistoryFile {
#[cfg(test)]
mod tests {
use crate::app_config::ConsumptionHistoryType;
use crate::energy::consumption::EnergyConsumption;
use crate::energy::consumption_history_file::{ConsumptionHistoryFile, TIME_INTERVAL};
#[test]
fn test_consumption_history() {
let mut history = ConsumptionHistoryFile::new_memory(0);
let mut history =
ConsumptionHistoryFile::new_memory(0, ConsumptionHistoryType::GridConsumption);
for i in 0..50 {
assert_eq!(

View File

@@ -195,6 +195,27 @@ impl Handler<UpdateDeviceGeneralInfo> for EnergyActor {
}
}
/// Set device desired version
#[derive(Message)]
#[rtype(result = "anyhow::Result<()>")]
pub struct SetDesiredVersion(pub DeviceId, pub Option<semver::Version>);
impl Handler<SetDesiredVersion> for EnergyActor {
type Result = anyhow::Result<()>;
fn handle(&mut self, msg: SetDesiredVersion, _ctx: &mut Context<Self>) -> Self::Result {
log::info!(
"Requested to update device desired version {:?} => {:#?}",
&msg.0,
&msg.1
);
self.devices.set_desired_version(&msg.0, msg.1)?;
Ok(())
}
}
/// Delete a device
#[derive(Message)]
#[rtype(result = "anyhow::Result<()>")]
@@ -378,8 +399,8 @@ impl Handler<GetDevicesState> for EnergyActor {
#[derive(serde::Serialize)]
pub struct ResRelayState {
pub id: DeviceRelayID,
on: bool,
r#for: usize,
pub on: bool,
pub r#for: usize,
}
/// Get the state of all relays

View File

@@ -8,7 +8,7 @@ use crate::devices::device::{Device, DeviceId, DeviceRelay, DeviceRelayID};
use crate::energy::consumption::EnergyConsumption;
use crate::energy::relay_state_history;
use crate::energy::relay_state_history::RelayStateHistory;
use crate::utils::time_utils::{curr_hour, time_secs, time_start_of_day};
use crate::utils::time_utils::{curr_hour, time_secs};
#[derive(Default)]
pub struct DeviceState {
@@ -283,12 +283,7 @@ impl EnergyEngine {
continue;
}
let time_start_day = time_start_of_day().unwrap_or(1726696800);
let start_time = time_start_day + constraints.reset_time as u64;
let end_time = time_start_day + 3600 * 24 + constraints.reset_time as u64;
let total_runtime =
relay_state_history::relay_total_runtime(r.id, start_time, end_time)
.unwrap_or(3600 * 24);
let total_runtime = relay_state_history::relay_total_runtime_adjusted(r);
if total_runtime > constraints.min_runtime {
continue;
@@ -454,7 +449,7 @@ mod test {
fn run_test(name: &str, conf: &str) {
let (devices, mut energy_engine, consumption, states) = parse_test_config(conf);
energy_engine.refresh(consumption, &devices);
energy_engine.refresh(consumption, &devices.iter().collect::<Vec<_>>());
for (device_s, device) in states.iter().zip(&devices) {
for (relay_s, relay) in device_s.relays.iter().zip(&device.relays) {

View File

@@ -1,7 +1,7 @@
use crate::app_config::AppConfig;
use crate::devices::device::DeviceRelayID;
use crate::devices::device::{DeviceRelay, DeviceRelayID};
use crate::utils::files_utils;
use crate::utils::time_utils::day_number;
use crate::utils::time_utils::{day_number, time_start_of_day};
const TIME_INTERVAL: usize = 30;
@@ -119,6 +119,20 @@ pub fn relay_total_runtime(device_id: DeviceRelayID, from: u64, to: u64) -> anyh
Ok(total)
}
/// Get the total runtime of a relay taking account of daily reset time
pub fn relay_total_runtime_adjusted(relay: &DeviceRelay) -> usize {
let reset_time = relay
.daily_runtime
.as_ref()
.map(|r| r.reset_time)
.unwrap_or(0);
let time_start_day = time_start_of_day().unwrap_or(1726696800);
let start_time = time_start_day + reset_time as u64;
let end_time = time_start_day + 3600 * 24 + reset_time as u64;
relay_total_runtime(relay.id, start_time, end_time).unwrap_or(3600 * 24)
}
#[cfg(test)]
mod tests {
use crate::devices::device::DeviceRelayID;

View File

@@ -3,5 +3,7 @@ pub mod constants;
pub mod crypto;
pub mod devices;
pub mod energy;
pub mod logs;
pub mod ota;
pub mod server;
pub mod utils;

View File

@@ -0,0 +1,17 @@
use crate::devices::device::DeviceId;
use crate::logs::severity::LogSeverity;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct LogEntry {
/// If no device is specified then the message comes from the backend
pub device_id: Option<DeviceId>,
pub time: u64,
pub severity: LogSeverity,
pub message: String,
}
impl LogEntry {
pub fn serialize(&self) -> anyhow::Result<String> {
Ok(serde_json::to_string(self)?)
}
}

View File

@@ -0,0 +1,58 @@
use crate::app_config::AppConfig;
use crate::devices::device::DeviceId;
use crate::logs::log_entry::LogEntry;
use crate::logs::severity::LogSeverity;
use crate::utils::time_utils::{curr_day_number, time_secs};
use fs4::fs_std::FileExt;
use std::fs::OpenOptions;
use std::io::{Seek, SeekFrom, Write};
pub fn save_log(
device: Option<&DeviceId>,
severity: LogSeverity,
message: String,
) -> anyhow::Result<()> {
let log_path = AppConfig::get().log_of_day(curr_day_number());
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(&log_path)?;
file.lock_exclusive()?;
file.seek(SeekFrom::End(0))?;
file.write_all(
format!(
"{}\n",
(LogEntry {
device_id: device.cloned(),
time: time_secs(),
severity,
message,
})
.serialize()?
)
.as_bytes(),
)?;
file.flush()?;
file.unlock()?;
Ok(())
}
/// Make a logs extraction
pub fn get_logs(day: u64) -> anyhow::Result<Vec<LogEntry>> {
let file = AppConfig::get().log_of_day(day);
if !file.exists() {
return Ok(Vec::new());
}
let content = std::fs::read_to_string(file)?
.split('\n')
.filter(|l| !l.is_empty())
.map(serde_json::from_str)
.collect::<Result<Vec<_>, _>>()?;
Ok(content)
}

View File

@@ -0,0 +1,3 @@
pub mod log_entry;
pub mod logs_manager;
pub mod severity;

View File

@@ -0,0 +1,7 @@
#[derive(serde::Serialize, serde::Deserialize, Copy, Clone, Debug, PartialOrd, Eq, PartialEq)]
pub enum LogSeverity {
Debug = 0,
Info,
Warn,
Error,
}

View File

@@ -9,6 +9,9 @@ use tokio_schedule::{every, Job};
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// Load additional config from file, if requested
AppConfig::parse_env_file().expect("Failed to parse environment file!");
// Initialize OpenSSL
openssl_sys::init();
@@ -19,6 +22,8 @@ async fn main() -> std::io::Result<()> {
create_directory_if_missing(AppConfig::get().devices_config_path()).unwrap();
create_directory_if_missing(AppConfig::get().relays_runtime_stats_storage_path()).unwrap();
create_directory_if_missing(AppConfig::get().energy_consumption_history()).unwrap();
create_directory_if_missing(AppConfig::get().logs_dir()).unwrap();
create_directory_if_missing(AppConfig::get().ota_dir()).unwrap();
// Initialize PKI
pki::initialize_root_ca().expect("Failed to initialize Root CA!");
@@ -42,8 +47,8 @@ async fn main() -> std::io::Result<()> {
.expect("Failed to initialize energy actor!")
.start();
let s1 = servers::secure_server(actor);
let s2 = servers::unsecure_server();
let s1 = servers::secure_server(actor.clone());
let s2 = servers::unsecure_server(actor);
future::try_join(s1, s2)
.await
.expect("Failed to start servers!");

View File

@@ -0,0 +1,2 @@
pub mod ota_manager;
pub mod ota_update;

View File

@@ -0,0 +1,74 @@
use crate::app_config::AppConfig;
use crate::ota::ota_update::{OTAPlatform, OTAUpdate};
use crate::utils::files_utils;
use std::os::unix::fs::MetadataExt;
use std::str::FromStr;
/// Check out whether a given update exists or not
pub fn update_exists(platform: OTAPlatform, version: &semver::Version) -> anyhow::Result<bool> {
Ok(AppConfig::get()
.path_ota_update(platform, version)
.is_file())
}
/// Save a new firmware update
pub fn save_update(
platform: OTAPlatform,
version: &semver::Version,
update: &[u8],
) -> anyhow::Result<()> {
let path = AppConfig::get().path_ota_update(platform, version);
files_utils::create_directory_if_missing(path.parent().unwrap())?;
std::fs::write(path, update)?;
Ok(())
}
/// Get the content of an OTA update
pub fn get_ota_update(platform: OTAPlatform, version: &semver::Version) -> anyhow::Result<Vec<u8>> {
let path = AppConfig::get().path_ota_update(platform, version);
Ok(std::fs::read(path)?)
}
/// Delete an OTA update
pub fn delete_update(platform: OTAPlatform, version: &semver::Version) -> anyhow::Result<()> {
let path = AppConfig::get().path_ota_update(platform, version);
std::fs::remove_file(path)?;
Ok(())
}
/// Get the list of OTA software updates for a platform
pub fn get_ota_updates_for_platform(platform: OTAPlatform) -> anyhow::Result<Vec<OTAUpdate>> {
let ota_path = AppConfig::get().ota_platform_dir(platform);
// Check if the directory dedicated to the updates of the platform exists
if !ota_path.is_dir() {
return Ok(Vec::new());
}
let mut out = Vec::new();
for e in std::fs::read_dir(ota_path)? {
let e = e?;
out.push(OTAUpdate {
platform,
version: semver::Version::from_str(e.file_name().to_str().unwrap_or("bad"))?,
file_size: e.metadata()?.size(),
});
}
Ok(out)
}
/// Get all the available OTA updates
pub fn get_all_ota_updates() -> anyhow::Result<Vec<OTAUpdate>> {
let mut out = vec![];
for p in OTAPlatform::supported_platforms() {
out.append(&mut get_ota_updates_for_platform(*p)?)
}
Ok(out)
}

View File

@@ -0,0 +1,38 @@
use std::fmt::{Display, Formatter};
use std::str::FromStr;
#[derive(serde::Serialize, serde::Deserialize, Debug, Copy, Clone, Eq, PartialEq)]
pub enum OTAPlatform {
#[serde(rename = "Wt32-Eth01")]
Wt32Eth01,
}
impl OTAPlatform {
/// Get the list of supported platforms
pub fn supported_platforms() -> &'static [Self] {
&[OTAPlatform::Wt32Eth01]
}
}
impl Display for OTAPlatform {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let s = serde_json::to_string(&self).unwrap().replace('"', "");
write!(f, "{s}")
}
}
impl FromStr for OTAPlatform {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(serde_json::from_str::<Self>(&format!("\"{s}\""))?)
}
}
/// Single OTA update information
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)]
pub struct OTAUpdate {
pub platform: OTAPlatform,
pub version: semver::Version,
pub file_size: u64,
}

View File

@@ -0,0 +1,22 @@
use crate::logs::logs_manager;
use crate::logs::severity::LogSeverity;
use crate::server::custom_error::HttpResult;
use crate::server::devices_api::jwt_parser::JWTRequest;
use crate::server::WebEnergyActor;
use actix_web::{web, HttpResponse};
#[derive(Debug, serde::Deserialize)]
pub struct LogRequest {
severity: LogSeverity,
message: String,
}
/// Report log message from device
pub async fn report_log(body: web::Json<JWTRequest>, actor: WebEnergyActor) -> HttpResult {
let (device, request) = body.parse_jwt::<LogRequest>(actor).await?;
log::info!("Save log message from device: {request:#?}");
logs_manager::save_log(Some(&device.id), request.severity, request.message)?;
Ok(HttpResponse::Accepted().finish())
}

View File

@@ -0,0 +1,21 @@
use crate::ota::ota_manager;
use crate::ota::ota_update::OTAPlatform;
use crate::server::custom_error::HttpResult;
use actix_web::{web, HttpResponse};
#[derive(serde::Deserialize)]
pub struct FirmwarePath {
platform: OTAPlatform,
version: semver::Version,
}
/// Download firmware update
pub async fn retrieve_firmware(path: web::Path<FirmwarePath>) -> HttpResult {
if !ota_manager::update_exists(path.platform, &path.version)? {
return Ok(HttpResponse::NotFound().json("The requested firmware was not found!"));
}
let firmware = ota_manager::get_ota_update(path.platform, &path.version)?;
Ok(HttpResponse::Ok().body(firmware))
}

View File

@@ -0,0 +1,96 @@
use crate::app_config::AppConfig;
use crate::crypto::pki;
use crate::devices::device::{Device, DeviceId};
use crate::energy::energy_actor;
use crate::server::WebEnergyActor;
use jsonwebtoken::{Algorithm, DecodingKey, Validation};
use openssl::x509::X509;
use serde::de::DeserializeOwned;
use std::collections::HashSet;
#[derive(thiserror::Error, Debug)]
pub enum JWTError {
#[error("Failed to decode JWT header")]
FailedDecodeJWT,
#[error("Missing KID in JWT!")]
MissingKidInJWT,
#[error("Sent a JWT for a device which does not exists!")]
DeviceDoesNotExists,
#[error("Sent a JWT for a device which is not validated!")]
DeviceNotValidated,
#[error("Sent a JWT using a revoked certificate!")]
RevokedCertificate,
#[error("Failed to validate JWT!")]
FailedValidateJWT,
}
#[derive(serde::Deserialize)]
pub struct JWTRequest {
pub payload: String,
}
impl JWTRequest {
pub async fn parse_jwt<E: DeserializeOwned>(
&self,
actor: WebEnergyActor,
) -> anyhow::Result<(Device, E)> {
// First, we need to extract device kid from query
let Ok(jwt_header) = jsonwebtoken::decode_header(&self.payload) else {
log::error!("Failed to decode JWT header!");
return Err(JWTError::FailedDecodeJWT.into());
};
let Some(kid) = jwt_header.kid else {
log::error!("Missing KID in JWT!");
return Err(JWTError::MissingKidInJWT.into());
};
// Fetch device information
let Some(device) = actor
.send(energy_actor::GetSingleDevice(DeviceId(kid)))
.await?
else {
log::error!("Sent a JWT for a device which does not exists!");
return Err(JWTError::DeviceDoesNotExists.into());
};
if !device.validated {
log::error!("Sent a JWT for a device which is not validated!");
return Err(JWTError::DeviceNotValidated.into());
}
// Check certificate revocation status
let cert_bytes = std::fs::read(AppConfig::get().device_cert_path(&device.id))?;
let certificate = X509::from_pem(&cert_bytes)?;
if pki::CertData::load_devices_ca()?.is_revoked(&certificate)? {
log::error!("Sent a JWT using a revoked certificate!");
return Err(JWTError::RevokedCertificate.into());
}
let (key, alg) = match DecodingKey::from_ec_pem(&cert_bytes) {
Ok(key) => (key, Algorithm::ES256),
Err(e) => {
log::warn!("Failed to decode certificate as EC certificate {e}, trying RSA...");
(
DecodingKey::from_rsa_pem(&cert_bytes)
.expect("Failed to decode RSA certificate"),
Algorithm::RS256,
)
}
};
let mut validation = Validation::new(alg);
validation.validate_exp = false;
validation.required_spec_claims = HashSet::default();
let c = match jsonwebtoken::decode::<E>(&self.payload, &key, &validation) {
Ok(c) => c,
Err(e) => {
log::error!("Failed to validate JWT! {e}");
return Err(JWTError::FailedValidateJWT.into());
}
};
Ok((device, c.claims))
}
}

View File

@@ -1,14 +1,16 @@
use crate::app_config::AppConfig;
use crate::crypto::pki;
use crate::devices::device::{DeviceId, DeviceInfo};
use crate::energy::energy_actor;
use crate::energy::energy_actor::RelaySyncStatus;
use crate::ota::ota_manager;
use crate::ota::ota_update::OTAPlatform;
use crate::server::custom_error::HttpResult;
use crate::server::devices_api::jwt_parser::JWTRequest;
use crate::server::WebEnergyActor;
use actix_web::{web, HttpResponse};
use jsonwebtoken::{Algorithm, DecodingKey, Validation};
use openssl::nid::Nid;
use openssl::x509::{X509Req, X509};
use std::collections::HashSet;
use openssl::x509::X509Req;
use std::str::FromStr;
#[derive(Debug, serde::Deserialize)]
pub struct EnrollRequest {
@@ -128,80 +130,41 @@ pub async fn get_certificate(query: web::Query<ReqWithDevID>, actor: WebEnergyAc
.body(cert))
}
#[derive(serde::Deserialize)]
pub struct SyncRequest {
payload: String,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Claims {
info: DeviceInfo,
}
#[derive(serde::Serialize)]
struct SyncResult {
relays: Vec<RelaySyncStatus>,
available_update: Option<semver::Version>,
}
/// Synchronize device
pub async fn sync_device(body: web::Json<SyncRequest>, actor: WebEnergyActor) -> HttpResult {
// First, we need to extract device kid from query
let Ok(jwt_header) = jsonwebtoken::decode_header(&body.payload) else {
log::error!("Failed to decode JWT header!");
return Ok(HttpResponse::BadRequest().json("Failed to decode JWT header!"));
};
pub async fn sync_device(body: web::Json<JWTRequest>, actor: WebEnergyActor) -> HttpResult {
let (device, claims) = body.0.parse_jwt::<Claims>(actor.clone()).await?;
let Some(kid) = jwt_header.kid else {
log::error!("Missing KID in JWT!");
return Ok(HttpResponse::BadRequest().json("Missing KID in JWT!"));
};
// Fetch device information
let Some(device) = actor
.send(energy_actor::GetSingleDevice(DeviceId(kid)))
.await?
else {
log::error!("Sent a JWT for a device which does not exists!");
return Ok(HttpResponse::NotFound().json("Sent a JWT for a device which does not exists!"));
};
if !device.validated {
log::error!("Sent a JWT for a device which is not validated!");
return Ok(HttpResponse::PreconditionFailed()
.json("Sent a JWT for a device which is not validated!"));
}
// Check certificate revocation status
let cert_bytes = std::fs::read(AppConfig::get().device_cert_path(&device.id))?;
let certificate = X509::from_pem(&cert_bytes)?;
if pki::CertData::load_devices_ca()?.is_revoked(&certificate)? {
log::error!("Sent a JWT using a revoked certificate!");
return Ok(
HttpResponse::PreconditionFailed().json("Sent a JWT using a revoked certificate!")
);
}
let (key, alg) = match DecodingKey::from_ec_pem(&cert_bytes) {
Ok(key) => (key, Algorithm::ES256),
Err(e) => {
log::warn!("Failed to decode certificate as EC certificate {e}, trying RSA...");
(
DecodingKey::from_rsa_pem(&cert_bytes).expect("Failed to decode RSA certificate"),
Algorithm::RS256,
)
}
};
let mut validation = Validation::new(alg);
validation.validate_exp = false;
validation.required_spec_claims = HashSet::default();
let c = match jsonwebtoken::decode::<Claims>(&body.payload, &key, &validation) {
Ok(c) => c,
Err(e) => {
log::error!("Failed to validate JWT! {e}");
return Ok(HttpResponse::PreconditionFailed().json("Failed to validate JWT!"));
}
};
let res = actor
.send(energy_actor::SynchronizeDevice(device.id, c.claims.info))
let relays = actor
.send(energy_actor::SynchronizeDevice(
device.id,
claims.info.clone(),
))
.await??;
Ok(HttpResponse::Ok().json(res))
let mut available_update = None;
// Check if the version is available
if let Some(desired) = device.desired_version {
if claims.info.version < desired
&& ota_manager::update_exists(OTAPlatform::from_str(&claims.info.reference)?, &desired)?
{
available_update = Some(desired);
}
}
Ok(HttpResponse::Ok().json(SyncResult {
relays,
available_update,
}))
}

View File

@@ -1,2 +1,5 @@
pub mod device_logging_controller;
pub mod devices_ota;
pub mod jwt_parser;
pub mod mgmt_controller;
pub mod utils_controller;

View File

@@ -3,7 +3,9 @@ use crate::constants;
use crate::crypto::pki;
use crate::energy::energy_actor::EnergyActorAddr;
use crate::server::auth_middleware::AuthChecker;
use crate::server::devices_api::{mgmt_controller, utils_controller};
use crate::server::devices_api::{
device_logging_controller, devices_ota, mgmt_controller, utils_controller,
};
use crate::server::unsecure_server::*;
use crate::server::web_api::*;
use crate::server::web_app_controller;
@@ -20,14 +22,15 @@ use openssl::ssl::{SslAcceptor, SslMethod};
use std::time::Duration;
/// Start unsecure (HTTP) server
pub async fn unsecure_server() -> anyhow::Result<()> {
pub async fn unsecure_server(energy_actor: EnergyActorAddr) -> anyhow::Result<()> {
log::info!(
"Unsecure server starting to listen on {} for {}",
AppConfig::get().unsecure_listen_address,
AppConfig::get().unsecure_origin()
);
HttpServer::new(|| {
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(energy_actor.clone()))
.wrap(Logger::default())
.route(
"/",
@@ -41,6 +44,10 @@ pub async fn unsecure_server() -> anyhow::Result<()> {
"/pki/{file}",
web::get().to(unsecure_pki_controller::serve_pki_file),
)
.route(
"/relay/{id}/legacy_state",
web::get().to(unsecure_relay_controller::legacy_state),
)
})
.bind(&AppConfig::get().unsecure_listen_address)?
.run()
@@ -180,6 +187,37 @@ pub async fn secure_server(energy_actor: EnergyActorAddr) -> anyhow::Result<()>
"/web_api/device/{id}",
web::delete().to(devices_controller::delete_device),
)
// OTA API
.route(
"/web_api/ota/supported_platforms",
web::get().to(ota_controller::supported_platforms),
)
.route(
"/web_api/ota/{platform}/{version}",
web::post().to(ota_controller::upload_firmware),
)
.route(
"/web_api/ota/{platform}/{version}",
web::get().to(ota_controller::download_firmware),
)
.route(
"/web_api/ota/{platform}/{version}",
web::delete().to(ota_controller::delete_update),
)
.route("/web_api/ota", web::get().to(ota_controller::list_all_ota))
.route(
"/web_api/ota/{platform}",
web::get().to(ota_controller::list_updates_platform),
)
.route(
"/web_api/ota/set_desired_version",
web::post().to(ota_controller::set_desired_version),
)
// Logging controller API
.route(
"/web_api/logging/logs",
web::get().to(logging_controller::get_log),
)
// Relays API
.route(
"/web_api/relays/list",
@@ -226,6 +264,14 @@ pub async fn secure_server(energy_actor: EnergyActorAddr) -> anyhow::Result<()>
"/devices_api/mgmt/sync",
web::post().to(mgmt_controller::sync_device),
)
.route(
"/devices_api/ota/{platform}/{version}",
web::get().to(devices_ota::retrieve_firmware),
)
.route(
"/devices_api/logging/record",
web::post().to(device_logging_controller::report_log),
)
// Web app
.route("/", web::get().to(web_app_controller::root_index))
.route(

View File

@@ -1,2 +1,3 @@
pub mod unsecure_pki_controller;
pub mod unsecure_relay_controller;
pub mod unsecure_server_controller;

View File

@@ -0,0 +1,60 @@
use crate::devices::device::DeviceRelayID;
use crate::energy::{energy_actor, relay_state_history};
use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor;
use actix_web::{web, HttpResponse};
#[derive(serde::Deserialize)]
pub struct LegacyStateRelay {
id: DeviceRelayID,
}
/// Legacy relay state
#[derive(serde::Serialize)]
pub struct LegacyState {
/// Indicates if relay is on or off
is_on: bool,
/// Relay name
name: String,
/// Duration since last change of state
r#for: usize,
/// Current grid consumption
prod: i32,
/// Total uptime since last reset
total_uptime: usize,
/// Required uptime during a day
///
/// Will be 0 if there is no daily requirements
required_uptime: usize,
}
/// Get the state of a relay, adapted for old system components
pub async fn legacy_state(
energy_actor: WebEnergyActor,
path: web::Path<LegacyStateRelay>,
) -> HttpResult {
let Some(relay) = energy_actor
.send(energy_actor::GetSingleRelay(path.id))
.await?
else {
return Ok(HttpResponse::NotFound().body("Relay not found!"));
};
let all_states = energy_actor.send(energy_actor::GetAllRelaysState).await?;
let Some(state) = all_states.into_iter().find(|r| r.id == path.id) else {
return Ok(HttpResponse::InternalServerError().body("Relay status unavailable!"));
};
let production = energy_actor.send(energy_actor::GetCurrConsumption).await?;
let total_uptime = relay_state_history::relay_total_runtime_adjusted(&relay);
Ok(HttpResponse::Ok().json(LegacyState {
name: relay.name,
is_on: state.on,
r#for: state.r#for.min(3600 * 24 * 7),
prod: production,
total_uptime,
required_uptime: relay.daily_runtime.map(|r| r.min_runtime).unwrap_or(0),
}))
}

View File

@@ -0,0 +1,30 @@
use crate::devices::device::DeviceId;
use crate::logs::logs_manager;
use crate::logs::severity::LogSeverity;
use crate::server::custom_error::HttpResult;
use crate::utils::time_utils::curr_day_number;
use actix_web::{web, HttpResponse};
#[derive(serde::Deserialize)]
pub struct LogRequest {
// Day number
day: Option<u64>,
min_severity: Option<LogSeverity>,
device: Option<DeviceId>,
}
/// Get some logs
pub async fn get_log(req: web::Query<LogRequest>) -> HttpResult {
let day = req.day.unwrap_or_else(curr_day_number);
let mut logs = logs_manager::get_logs(day)?;
if let Some(min_severity) = req.min_severity {
logs.retain(|d| d.severity >= min_severity);
}
if let Some(dev_id) = &req.device {
logs.retain(|d| d.device_id.as_ref() == Some(dev_id));
}
Ok(HttpResponse::Ok().json(logs))
}

View File

@@ -1,5 +1,7 @@
pub mod auth_controller;
pub mod devices_controller;
pub mod energy_controller;
pub mod logging_controller;
pub mod ota_controller;
pub mod relays_controller;
pub mod server_controller;

View File

@@ -0,0 +1,148 @@
use crate::constants;
use crate::devices::device::DeviceId;
use crate::energy::energy_actor;
use crate::ota::ota_manager;
use crate::ota::ota_update::OTAPlatform;
use crate::server::custom_error::HttpResult;
use crate::server::WebEnergyActor;
use actix_multipart::form::tempfile::TempFile;
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpResponse};
pub async fn supported_platforms() -> HttpResult {
Ok(HttpResponse::Ok().json(OTAPlatform::supported_platforms()))
}
#[derive(Debug, MultipartForm)]
pub struct UploadForm {
#[multipart(rename = "firmware")]
firmware: Vec<TempFile>,
}
#[derive(serde::Deserialize)]
pub struct SpecificOTAVersionPath {
platform: OTAPlatform,
version: semver::Version,
}
/// Upload a new firmware update
pub async fn upload_firmware(
MultipartForm(form): MultipartForm<UploadForm>,
path: web::Path<SpecificOTAVersionPath>,
) -> HttpResult {
if ota_manager::update_exists(path.platform, &path.version)? {
return Ok(HttpResponse::Conflict()
.json("A firmware with the same version has already been uploaded on the platform!"));
}
let Some(file) = form.firmware.first() else {
return Ok(HttpResponse::BadRequest().json("No firmware specified!"));
};
if file.size == 0 {
return Ok(HttpResponse::BadRequest().json("Uploaded file is empty!"));
}
if file.size > constants::MAX_FIRMWARE_SIZE {
return Ok(HttpResponse::BadRequest().json("Uploaded file is too heavy!"));
}
let content = std::fs::read(file.file.path())?;
ota_manager::save_update(path.platform, &path.version, &content)?;
Ok(HttpResponse::Accepted().body("OTA update successfully saved."))
}
/// Download a firmware update
pub async fn download_firmware(path: web::Path<SpecificOTAVersionPath>) -> HttpResult {
if !ota_manager::update_exists(path.platform, &path.version)? {
return Ok(HttpResponse::NotFound().json("The requested firmware update was not found!"));
}
let firmware = ota_manager::get_ota_update(path.platform, &path.version)?;
Ok(HttpResponse::Ok()
.content_type("application/octet-stream")
.append_header((
"content-disposition",
format!(
"attachment; filename=\"{}-{}.bin\"",
path.platform, path.version
),
))
.body(firmware))
}
/// Delete an uploaded firmware update
pub async fn delete_update(path: web::Path<SpecificOTAVersionPath>) -> HttpResult {
if !ota_manager::update_exists(path.platform, &path.version)? {
return Ok(HttpResponse::NotFound().json("The requested firmware update was not found!"));
}
ota_manager::delete_update(path.platform, &path.version)?;
Ok(HttpResponse::Accepted().finish())
}
/// Get the list of all OTA updates
pub async fn list_all_ota() -> HttpResult {
Ok(HttpResponse::Ok().json(ota_manager::get_all_ota_updates()?))
}
#[derive(serde::Deserialize)]
pub struct ListOTAPath {
platform: OTAPlatform,
}
/// List OTA software updates for a given platform
pub async fn list_updates_platform(path: web::Path<ListOTAPath>) -> HttpResult {
let list = ota_manager::get_ota_updates_for_platform(path.platform)?;
Ok(HttpResponse::Ok().json(list))
}
#[derive(serde::Deserialize)]
pub struct SetDesiredDeviceVersion {
devices: Option<Vec<DeviceId>>,
platform: Option<OTAPlatform>,
version: semver::Version,
}
pub async fn set_desired_version(
actor: WebEnergyActor,
body: web::Json<SetDesiredDeviceVersion>,
) -> HttpResult {
if body.devices.is_none() && body.platform.is_none() {
return Ok(
HttpResponse::BadRequest().json("Must specify one filter to select target devices!")
);
}
let devices = actor.send(energy_actor::GetDeviceLists).await?;
for d in devices {
// Filter per platform
if let Some(p) = body.platform {
if d.info.reference != p.to_string() {
continue;
}
}
// Filter per device
if let Some(ids) = &body.devices {
if !ids.contains(&d.id) {
continue;
}
}
actor
.send(energy_actor::SetDesiredVersion(
d.id,
Some(body.version.clone()),
))
.await??;
}
Ok(HttpResponse::Ok().finish())
}

View File

@@ -12,6 +12,7 @@ pub async fn secure_home() -> HttpResponse {
struct ServerConfig {
auth_disabled: bool,
constraints: StaticConstraints,
unsecure_origin: String,
}
impl Default for ServerConfig {
@@ -19,6 +20,7 @@ impl Default for ServerConfig {
Self {
auth_disabled: AppConfig::get().unsecure_disable_login,
constraints: Default::default(),
unsecure_origin: AppConfig::get().unsecure_origin(),
}
}
}

View File

@@ -1,3 +1,3 @@
pub mod files_utils;
pub mod math_utils;
pub mod math_utils;
pub mod time_utils;

View File

@@ -22,6 +22,11 @@ pub fn day_number(time: u64) -> u64 {
time / (3600 * 24)
}
/// Get current day number
pub fn curr_day_number() -> u64 {
day_number(time_secs())
}
/// Get current hour, 00 => 23 (local time)
pub fn curr_hour() -> u32 {
let local: DateTime<Local> = Local::now();

View File

@@ -1,30 +0,0 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
- Configure the top-level `parserOptions` property like this:
```js
export default {
// other rules...
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig.node.json'],
tsconfigRootDir: __dirname,
},
}
```
- Replace `plugin:@typescript-eslint/recommended` to `plugin:@typescript-eslint/recommended-type-checked` or `plugin:@typescript-eslint/strict-type-checked`
- Optionally add `plugin:@typescript-eslint/stylistic-type-checked`
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and add `plugin:react/recommended` & `plugin:react/jsx-runtime` to the `extends` list

View File

@@ -2,7 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/sunny.svg" />
<link rel="icon" type="image/svg+xml" href="/assets/sunny.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>SolarEnergy</title>
</head>

File diff suppressed because it is too large Load Diff

View File

@@ -15,26 +15,29 @@
"@fontsource/roboto": "^5.1.0",
"@mdi/js": "^7.4.47",
"@mdi/react": "^1.6.1",
"@mui/icons-material": "^6.1.1",
"@mui/material": "^6.1.1",
"@mui/x-charts": "^7.18.0",
"@mui/x-date-pickers": "^7.18.0",
"date-and-time": "^3.5.0",
"@mui/icons-material": "^6.1.3",
"@mui/material": "^6.1.3",
"@mui/x-charts": "^7.20.0",
"@mui/x-date-pickers": "^7.20.0",
"@types/semver": "^7.5.8",
"date-and-time": "^3.6.0",
"dayjs": "^1.11.13",
"filesize": "^10.1.6",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"react-router-dom": "^6.26.2"
"react-router-dom": "^6.27.0",
"semver": "^7.6.3"
},
"devDependencies": {
"@types/react": "^18.3.8",
"@types/react-dom": "^18.3.0",
"@typescript-eslint/eslint-plugin": "^8.6.0",
"@typescript-eslint/parser": "^8.6.0",
"@vitejs/plugin-react": "^4.3.1",
"@types/react": "^18.3.11",
"@types/react-dom": "^18.3.1",
"@typescript-eslint/eslint-plugin": "^8.8.0",
"@typescript-eslint/parser": "^8.8.0",
"@vitejs/plugin-react": "^4.3.2",
"eslint": "^8.57.1",
"eslint-plugin-react-hooks": "^4.6.2",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.12",
"typescript": "^5.6.2",
"vite": "^5.4.7"
"typescript": "^5.6.3",
"vite": "^5.4.8"
}
}

View File

Before

Width:  |  Height:  |  Size: 407 KiB

After

Width:  |  Height:  |  Size: 407 KiB

View File

Before

Width:  |  Height:  |  Size: 557 B

After

Width:  |  Height:  |  Size: 557 B

View File

@@ -10,10 +10,12 @@ import { DeviceRoute } from "./routes/DeviceRoute/DeviceRoute";
import { DevicesRoute } from "./routes/DevicesRoute";
import { HomeRoute } from "./routes/HomeRoute";
import { LoginRoute } from "./routes/LoginRoute";
import { LogsRoute } from "./routes/LogsRoute";
import { NotFoundRoute } from "./routes/NotFoundRoute";
import { PendingDevicesRoute } from "./routes/PendingDevicesRoute";
import { RelaysListRoute } from "./routes/RelaysListRoute";
import { BaseAuthenticatedPage } from "./widgets/BaseAuthenticatedPage";
import { OTARoute } from "./routes/OTARoute";
export function App() {
if (!AuthApi.SignedIn && !ServerApi.Config.auth_disabled)
@@ -27,6 +29,8 @@ export function App() {
<Route path="devices" element={<DevicesRoute />} />
<Route path="dev/:id" element={<DeviceRoute />} />
<Route path="relays" element={<RelaysListRoute />} />
<Route path="ota" element={<OTARoute />} />
<Route path="logs" element={<LogsRoute />} />
<Route path="*" element={<NotFoundRoute />} />
</Route>
)

View File

@@ -37,6 +37,7 @@ export interface Device {
validated: boolean;
enabled: boolean;
relays: DeviceRelay[];
desired_version?: string;
}
export interface UpdatedInfo {

View File

@@ -0,0 +1,29 @@
import { Dayjs } from "dayjs";
import { APIClient } from "./ApiClient";
export type LogSeverity = "Debug" | "Info" | "Warn" | "Error";
export interface LogEntry {
device_id: string;
time: number;
severity: LogSeverity;
message: string;
}
export class LogsAPI {
/**
* Request the logs from the server
*
* @param date The date that contains the requested date
*/
static async GetLogs(date: Dayjs): Promise<LogEntry[]> {
const day = Math.floor(date.unix() / (3600 * 24));
const res = await APIClient.exec({
uri: `/logging/logs?day=${day}`,
method: "GET",
});
return res.data;
}
}

View File

@@ -0,0 +1,87 @@
import { APIClient } from "./ApiClient";
export interface OTAUpdate {
platform: string;
version: string;
file_size: number;
}
export class OTAAPI {
/**
* Get the list of supported OTA platforms
*/
static async SupportedPlatforms(): Promise<Array<string>> {
return (
await APIClient.exec({
method: "GET",
uri: "/ota/supported_platforms",
})
).data;
}
/**
* Upload new OTA firwmare
*/
static async UploadFirmware(
platform: string,
version: string,
firmware: File
): Promise<void> {
const fd = new FormData();
fd.append("firmware", firmware);
await APIClient.exec({
method: "POST",
uri: `/ota/${platform}/${version}`,
formData: fd,
});
}
/**
* Get the link to download an OTA update
*/
static DownloadOTAUpdateURL(update: OTAUpdate): string {
return APIClient.backendURL() + `/ota/${update.platform}/${update.version}`;
}
/**
* Delete an update
*/
static async DeleteUpdate(update: OTAUpdate): Promise<void> {
await APIClient.exec({
method: "DELETE",
uri: `/ota/${update.platform}/${update.version}`,
});
}
/**
* Get the list of OTA updates
*/
static async ListOTAUpdates(): Promise<OTAUpdate[]> {
return (
await APIClient.exec({
method: "GET",
uri: "/ota",
})
).data;
}
/**
* Set desired version for one or mor devices
*/
static async SetDesiredVersion(
update: OTAUpdate,
all_devices: boolean,
devices?: string[]
): Promise<void> {
await APIClient.exec({
method: "POST",
uri: "/ota/set_desired_version",
jsonData: {
version: update.version,
platform: update.platform,
devices: all_devices ? undefined : devices!,
},
});
}
}

View File

@@ -3,6 +3,7 @@ import { APIClient } from "./ApiClient";
export interface ServerConfig {
auth_disabled: boolean;
constraints: ServerConstraint;
unsecure_origin: string;
}
export interface ServerConstraint {

View File

@@ -0,0 +1,148 @@
import {
Button,
Checkbox,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
FormControl,
FormControlLabel,
FormGroup,
FormLabel,
Radio,
RadioGroup,
Typography,
} from "@mui/material";
import React from "react";
import { Device, DeviceApi } from "../api/DeviceApi";
import { OTAAPI, OTAUpdate } from "../api/OTAApi";
import { useAlert } from "../hooks/context_providers/AlertDialogProvider";
import { useConfirm } from "../hooks/context_providers/ConfirmDialogProvider";
import { useLoadingMessage } from "../hooks/context_providers/LoadingMessageProvider";
import { useSnackbar } from "../hooks/context_providers/SnackbarProvider";
import { AsyncWidget } from "../widgets/AsyncWidget";
export function DeployOTAUpdateDialogProvider(p: {
update: OTAUpdate;
onClose: () => void;
}): React.ReactElement {
const loadingMessage = useLoadingMessage();
const alert = useAlert();
const confirm = useConfirm();
const snackbar = useSnackbar();
const [devicesList, setDevicesList] = React.useState<Device[] | undefined>();
const loadDevicesList = async () => {
let list = await DeviceApi.ValidatedList();
list = list.filter((e) => e.info.reference == p.update.platform);
setDevicesList(list);
};
const [allDevices, setAllDevices] = React.useState(false);
const [selectedDevices, setSelectedDevices] = React.useState<string[]>([]);
const startDeployment = async () => {
if (
allDevices &&
!(await confirm(
"Do you really want to deploy the update to all devices?"
))
)
return;
try {
loadingMessage.show("Applying OTA update...");
await OTAAPI.SetDesiredVersion(p.update, allDevices, selectedDevices);
snackbar("The update was successfully applied!");
p.onClose();
} catch (e) {
console.error("Failed to deploy the udpate!", e);
alert(`Failed to deploy the udpate! ${e}`);
} finally {
loadingMessage.hide();
}
};
return (
<Dialog open={true} onClose={p.onClose}>
<DialogTitle>
Deploy update <i>{p.update.version}</i> for platform{" "}
<i>{p.update.platform}</i>
</DialogTitle>
<AsyncWidget
loadKey={1}
load={loadDevicesList}
errMsg="Failed to load the list of devices!"
build={() => (
<DialogContent>
<DialogContentText>
You can choose to deploy update to all device or to target only a
part of devices:
</DialogContentText>
<FormControl>
<FormLabel>Gender</FormLabel>
<RadioGroup
name="radio-buttons-group"
value={allDevices}
onChange={(v) => setAllDevices(v.target.value == "true")}
>
<FormControlLabel
value={true}
control={<Radio />}
label="Deploy the update to all the devices of the platform"
/>
<FormControlLabel
value={false}
control={<Radio />}
label="Deploy the update to a limited range of devices"
/>
</RadioGroup>
</FormControl>
{!allDevices && (
<Typography>
There are no devices to which the update can be deployed.
</Typography>
)}
{!allDevices && (
<FormGroup>
{devicesList?.map((d) => (
<FormControlLabel
control={
<Checkbox
checked={selectedDevices.includes(d.id)}
onChange={(_e, v) => {
if (v) {
selectedDevices.push(d.id);
setSelectedDevices([...selectedDevices]);
} else
setSelectedDevices(
selectedDevices.filter((e) => e != d.id)
);
}}
/>
}
label={d.name}
/>
))}
</FormGroup>
)}
</DialogContent>
)}
/>
<DialogActions>
<Button onClick={p.onClose}>Cancel</Button>
<Button
onClick={startDeployment}
autoFocus
disabled={!allDevices && selectedDevices.length == 0}
>
Start deployment
</Button>
</DialogActions>
</Dialog>
);
}

View File

@@ -0,0 +1,132 @@
import CloudUploadIcon from "@mui/icons-material/CloudUpload";
import {
Button,
Dialog,
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
FormControl,
InputLabel,
MenuItem,
Select,
styled,
} from "@mui/material";
import React from "react";
import { OTAAPI } from "../api/OTAApi";
import { useAlert } from "../hooks/context_providers/AlertDialogProvider";
import { useLoadingMessage } from "../hooks/context_providers/LoadingMessageProvider";
import { useSnackbar } from "../hooks/context_providers/SnackbarProvider";
import { checkVersion } from "../utils/StringsUtils";
import { TextInput } from "../widgets/forms/TextInput";
const VisuallyHiddenInput = styled("input")({
clip: "rect(0 0 0 0)",
clipPath: "inset(50%)",
height: 1,
overflow: "hidden",
position: "absolute",
bottom: 0,
left: 0,
whiteSpace: "nowrap",
width: 1,
});
export function UploadUpdateDialog(p: {
platforms: string[];
onClose: () => void;
onCreated: () => void;
}): React.ReactElement {
const alert = useAlert();
const snackbar = useSnackbar();
const loadingMessage = useLoadingMessage();
const [platform, setPlatform] = React.useState<string | undefined>();
const [version, setVersion] = React.useState<string | undefined>();
const [file, setFile] = React.useState<File | undefined>();
const canSubmit = platform && version && checkVersion(version) && file;
const upload = async () => {
try {
loadingMessage.show("Uploading firmware...");
await OTAAPI.UploadFirmware(platform!, version!, file!);
snackbar("Successfully uploaded new firmware!");
p.onCreated();
} catch (e) {
console.error(e);
alert(`Failed to upload firmware: ${e}`);
} finally {
loadingMessage.hide();
}
};
return (
<Dialog open={true} onClose={p.onClose}>
<DialogTitle>Submit a new update</DialogTitle>
<DialogContent>
<DialogContentText>
You can upload a new firmware using this form.
</DialogContentText>
<br />
<FormControl fullWidth>
<InputLabel>Platform</InputLabel>
<Select
label="Platform"
value={platform}
onChange={(e) => setPlatform(e.target.value)}
variant="standard"
>
{p.platforms.map((p) => (
<MenuItem key={p} value={p}>
{p}
</MenuItem>
))}
</Select>
</FormControl>
<br />
<br />
<TextInput
editable
label="Version"
helperText="The version shall follow semantics requirements"
value={version}
onValueChange={setVersion}
checkValue={checkVersion}
/>
<br />
<Button
fullWidth
component="label"
role={undefined}
variant={file ? "contained" : "outlined"}
tabIndex={-1}
startIcon={<CloudUploadIcon />}
>
Upload file
<VisuallyHiddenInput
type="file"
onChange={(event) =>
setFile(
(event.target.files?.length ?? 0) > 0
? event.target.files![0]
: undefined
)
}
multiple
/>
</Button>
</DialogContent>
<DialogActions>
<Button onClick={p.onClose}>Cancel</Button>
<Button type="submit" disabled={!canSubmit} onClick={upload}>
Upload
</Button>
</DialogActions>
</Dialog>
);
}

View File

@@ -129,7 +129,9 @@ export function DeviceRelays(p: {
);
}
function RelayEntryStatus(p: { relay: DeviceRelay }): React.ReactElement {
function RelayEntryStatus(
p: Readonly<{ relay: DeviceRelay }>
): React.ReactElement {
const [state, setState] = React.useState<RelayStatus | undefined>();
const load = async () => {

View File

@@ -41,6 +41,10 @@ export function GeneralDeviceInfo(p: {
value={p.device.info.reference}
/>
<DeviceInfoProperty label="Version" value={p.device.info.version} />
<DeviceInfoProperty
label="Desired version"
value={p.device.desired_version ?? "None"}
/>
<DeviceInfoProperty label="Name" value={p.device.name} />
<DeviceInfoProperty
label="Description"

View File

@@ -62,7 +62,7 @@ export function LoginRoute() {
<Grid
size={{ sm: 4, md: 7, xs: false }}
sx={{
backgroundImage: 'url("/sun.jpg")',
backgroundImage: 'url("/assets/sun.jpg")',
backgroundColor: (t) =>
t.palette.mode === "light"
? t.palette.grey[50]

View File

@@ -0,0 +1,124 @@
import NavigateBeforeIcon from "@mui/icons-material/NavigateBefore";
import NavigateNextIcon from "@mui/icons-material/NavigateNext";
import RefreshIcon from "@mui/icons-material/Refresh";
import {
IconButton,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Tooltip,
Typography,
} from "@mui/material";
import { DatePicker } from "@mui/x-date-pickers";
import dayjs from "dayjs";
import React from "react";
import { LogEntry, LogsAPI } from "../api/LogsAPI";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { SolarEnergyRouteContainer } from "../widgets/SolarEnergyRouteContainer";
export function LogsRoute(): React.ReactElement {
const loadKey = React.useRef(1);
const [currDate, setCurrDate] = React.useState(dayjs());
const [logs, setLogs] = React.useState<LogEntry[] | undefined>();
const load = async () => {
const logs = await LogsAPI.GetLogs(currDate);
logs.reverse();
setLogs(logs);
};
const reload = () => {
setLogs(undefined);
loadKey.current += 1;
};
return (
<SolarEnergyRouteContainer
label="Logs"
actions={
<Tooltip title="Refresh logs">
<IconButton onClick={reload}>
<RefreshIcon />
</IconButton>
</Tooltip>
}
>
<div
style={{
width: "100%",
display: "flex",
alignItems: "center",
justifyContent: "center",
marginBottom: "10px",
}}
>
<Tooltip title="Previous day">
<IconButton onClick={() => setCurrDate(currDate.add(-1, "day"))}>
<NavigateBeforeIcon />
</IconButton>
</Tooltip>
<DatePicker
label="Shown day"
value={currDate}
onChange={(d) => setCurrDate(d === null ? currDate : d)}
/>
<Tooltip title="Next day">
<IconButton onClick={() => setCurrDate(currDate.add(1, "day"))}>
<NavigateNextIcon />
</IconButton>
</Tooltip>
</div>
<AsyncWidget
ready={!!logs}
loadKey={loadKey.current + currDate.toString()}
errMsg="Failed to load the logs!"
load={load}
build={() => <LogsView logs={logs!} />}
/>
</SolarEnergyRouteContainer>
);
}
function LogsView(p: { logs: LogEntry[] }): React.ReactElement {
if (p.logs.length == 0) {
return (
<Typography style={{ textAlign: "center" }}>
There was no log recorded on this day.
</Typography>
);
}
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} size="small" aria-label="a dense table">
<TableHead>
<TableRow>
<TableCell>Device ID</TableCell>
<TableCell>Time</TableCell>
<TableCell>Severity</TableCell>
<TableCell>Message</TableCell>
</TableRow>
</TableHead>
<TableBody>
{p.logs.map((row, id) => (
<TableRow key={id} hover>
<TableCell component="th" scope="row">
{row.device_id ?? "Backend"}
</TableCell>
<TableCell>
{new Date(row.time * 1000).toLocaleTimeString()}
</TableCell>
<TableCell>{row.severity}</TableCell>
<TableCell>{row.message}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
);
}

View File

@@ -0,0 +1,203 @@
import { mdiFolderUploadOutline } from "@mdi/js";
import Icon from "@mdi/react";
import DeleteIcon from "@mui/icons-material/Delete";
import DownloadIcon from "@mui/icons-material/Download";
import FileUploadIcon from "@mui/icons-material/FileUpload";
import RefreshIcon from "@mui/icons-material/Refresh";
import {
IconButton,
Paper,
Table,
TableBody,
TableCell,
TableContainer,
TableHead,
TableRow,
Tooltip,
Typography,
} from "@mui/material";
import { filesize } from "filesize";
import React from "react";
import { OTAAPI, OTAUpdate } from "../api/OTAApi";
import { DeployOTAUpdateDialogProvider } from "../dialogs/DeployOTAUpdateDialogProvider";
import { UploadUpdateDialog } from "../dialogs/UploadUpdateDialog";
import { useAlert } from "../hooks/context_providers/AlertDialogProvider";
import { useConfirm } from "../hooks/context_providers/ConfirmDialogProvider";
import { useLoadingMessage } from "../hooks/context_providers/LoadingMessageProvider";
import { useSnackbar } from "../hooks/context_providers/SnackbarProvider";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { RouterLink } from "../widgets/RouterLink";
import { SolarEnergyRouteContainer } from "../widgets/SolarEnergyRouteContainer";
export function OTARoute(): React.ReactElement {
const [list, setList] = React.useState<string[] | undefined>();
const load = async () => {
setList(await OTAAPI.SupportedPlatforms());
};
return (
<AsyncWidget
loadKey={1}
ready={!!list}
load={load}
errMsg="Failed to load OTA screen!"
build={() => <_OTARoute platforms={list!} />}
/>
);
}
function _OTARoute(p: { platforms: Array<string> }): React.ReactElement {
const key = React.useRef(1);
const [showUploadDialog, setShowUploadDialog] = React.useState(false);
const [list, setList] = React.useState<undefined | OTAUpdate[]>();
const load = async () => {
const list = await OTAAPI.ListOTAUpdates();
list.sort((a, b) =>
`${a.platform}#${a.version}`.localeCompare(`${b.platform}#${b.version}`)
);
list.reverse();
setList(list);
};
const reload = async () => {
key.current += 1;
setList(undefined);
};
return (
<SolarEnergyRouteContainer
label="OTA"
actions={
<span>
<Tooltip title="Refresh the list of updates">
<IconButton onClick={reload}>
<RefreshIcon />
</IconButton>
</Tooltip>
<Tooltip title="Upload a new update">
<IconButton onClick={() => setShowUploadDialog(true)}>
<FileUploadIcon />
</IconButton>
</Tooltip>
</span>
}
>
{showUploadDialog && (
<UploadUpdateDialog
platforms={p.platforms}
onClose={() => setShowUploadDialog(false)}
onCreated={() => {
setShowUploadDialog(false);
reload();
}}
/>
)}
<AsyncWidget
loadKey={key.current}
ready={!!list}
errMsg="Failed to load the list of OTA updates!"
load={load}
build={() => <_OTAList list={list!} onReload={reload} />}
/>
</SolarEnergyRouteContainer>
);
}
function _OTAList(p: {
list: OTAUpdate[];
onReload: () => void;
}): React.ReactElement {
const alert = useAlert();
const confirm = useConfirm();
const loadingMessage = useLoadingMessage();
const snackbar = useSnackbar();
const [deployUpdate, setDeployUpdate] = React.useState<
OTAUpdate | undefined
>();
const deleteUpdate = async (update: OTAUpdate) => {
if (
!(await confirm(
`Do you really want to delete the update for platform ${update.platform} version ${update.version}?`
))
)
return;
try {
loadingMessage.show("Deleting update...");
await OTAAPI.DeleteUpdate(update);
snackbar("The update was successfully deleted!");
p.onReload();
} catch (e) {
console.error("Failed to delete update!", e);
alert(`Failed to delete the update! ${e}`);
} finally {
loadingMessage.hide();
}
};
if (p.list.length === 0) {
return (
<Typography>
There is no OTA update uploaded on the platform yet.
</Typography>
);
}
return (
<>
{deployUpdate && (
<DeployOTAUpdateDialogProvider
update={deployUpdate!}
onClose={() => setDeployUpdate(undefined)}
/>
)}
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }} aria-label="list of updates">
<TableHead>
<TableRow>
<TableCell align="center">Platform</TableCell>
<TableCell align="center">Version</TableCell>
<TableCell align="center">File size</TableCell>
<TableCell align="center"></TableCell>
</TableRow>
</TableHead>
<TableBody>
{p.list.map((row, num) => (
<TableRow hover key={num}>
<TableCell align="center">{row.platform}</TableCell>
<TableCell align="center">{row.version}</TableCell>
<TableCell align="center">{filesize(row.file_size)}</TableCell>
<TableCell align="center">
<Tooltip title="Deploy the update to devices">
<IconButton onClick={() => setDeployUpdate(row)}>
<Icon path={mdiFolderUploadOutline} size={1} />
</IconButton>
</Tooltip>
<Tooltip title="Download a copy of the firmware">
<RouterLink to={OTAAPI.DownloadOTAUpdateURL(row)}>
<IconButton>
<DownloadIcon />
</IconButton>
</RouterLink>
</Tooltip>
<Tooltip title="Delete firmware update">
<IconButton onClick={() => deleteUpdate(row)}>
<DeleteIcon />
</IconButton>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</>
);
}

View File

@@ -1,3 +1,4 @@
import LinkIcon from "@mui/icons-material/Link";
import RefreshIcon from "@mui/icons-material/Refresh";
import {
IconButton,
@@ -9,16 +10,18 @@ import {
TableHead,
TableRow,
Tooltip,
Typography,
} from "@mui/material";
import React from "react";
import { useNavigate } from "react-router-dom";
import { Device, DeviceApi, DeviceRelay, DeviceURL } from "../api/DeviceApi";
import { RelayApi, RelaysStatus } from "../api/RelayApi";
import { AsyncWidget } from "../widgets/AsyncWidget";
import { BoolText } from "../widgets/BoolText";
import { SolarEnergyRouteContainer } from "../widgets/SolarEnergyRouteContainer";
import { TimeWidget } from "../widgets/TimeWidget";
import { EditDeviceRelaysDialog } from "../dialogs/EditDeviceRelaysDialog";
import { useNavigate } from "react-router-dom";
import { CopyToClipboard } from "../widgets/CopyToClipboard";
import { ServerApi } from "../api/ServerApi";
export function RelaysListRoute(p: {
homeWidget?: boolean;
@@ -87,6 +90,10 @@ function RelaysList(p: {
navigate(DeviceURL(dev!));
};
if (p.list.length === 0) {
return <Typography>There is no configured relay yet!</Typography>;
}
return (
<TableContainer component={Paper}>
<Table sx={{ minWidth: 650 }}>
@@ -97,6 +104,7 @@ function RelaysList(p: {
<TableCell>Priority</TableCell>
<TableCell>Consumption</TableCell>
<TableCell>Status</TableCell>
<TableCell></TableCell>
</TableRow>
</TableHead>
<TableBody>
@@ -121,6 +129,20 @@ function RelaysList(p: {
/>{" "}
for <TimeWidget diff time={p.status.get(row.id)!.for} />
</TableCell>
<TableCell>
<Tooltip title="Copy legacy api status">
<CopyToClipboard
content={
ServerApi.Config.unsecure_origin +
`/relay/${row.id}/legacy_state`
}
>
<IconButton>
<LinkIcon />
</IconButton>
</CopyToClipboard>
</Tooltip>
</TableCell>
</TableRow>
))}
</TableBody>

View File

@@ -1,3 +1,4 @@
import { SemVer } from "semver";
import { LenConstraint } from "../api/ServerApi";
/**
@@ -6,3 +7,16 @@ import { LenConstraint } from "../api/ServerApi";
export function lenValid(s: string, c: LenConstraint): boolean {
return s.length >= c.min && s.length <= c.max;
}
/**
* Check out whether a given version number respect semantics requirements or not
*/
export function checkVersion(v: string): boolean {
try {
new SemVer(v, { loose: false });
return true;
} catch (e) {
console.error(e);
return false;
}
}

View File

@@ -0,0 +1,30 @@
import { ButtonBase } from "@mui/material";
import { PropsWithChildren } from "react";
import { useSnackbar } from "../hooks/context_providers/SnackbarProvider";
export function CopyToClipboard(
p: PropsWithChildren<{ content: string }>
): React.ReactElement {
const snackbar = useSnackbar();
const copy = () => {
navigator.clipboard.writeText(p.content);
snackbar(`${p.content} copied to clipboard.`);
};
return (
<ButtonBase
onClick={copy}
style={{
display: "inline-block",
alignItems: "unset",
textAlign: "unset",
position: "relative",
padding: "0px",
}}
disableRipple
>
{p.children}
</ButtonBase>
);
}

View File

@@ -1,4 +1,11 @@
import { mdiChip, mdiElectricSwitch, mdiHome, mdiNewBox } from "@mdi/js";
import {
mdiChip,
mdiElectricSwitch,
mdiHome,
mdiMonitorArrowDown,
mdiNewBox,
mdiNotebookMultiple,
} from "@mdi/js";
import Icon from "@mdi/react";
import {
List,
@@ -35,6 +42,16 @@ export function SolarEnergyNavList(): React.ReactElement {
uri="/relays"
icon={<Icon path={mdiElectricSwitch} size={1} />}
/>
<NavLink
label="OTA"
uri="/ota"
icon={<Icon path={mdiMonitorArrowDown} size={1} />}
/>
<NavLink
label="Logging"
uri="/logs"
icon={<Icon path={mdiNotebookMultiple} size={1} />}
/>
</List>
);
}

View File

@@ -9,13 +9,20 @@ export function SolarEnergyRouteContainer(
} & PropsWithChildren
): React.ReactElement {
return (
<div style={{ margin: p.homeWidget ? "0px" : "50px" }}>
<div
style={{
margin: p.homeWidget ? "0px" : "50px",
flex: 1,
maxWidth: "1300px",
}}
>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "20px",
flex: 1,
}}
>
<Typography variant={p.homeWidget ? "h6" : "h4"}>{p.label}</Typography>

View File

@@ -697,9 +697,9 @@ dependencies = [
[[package]]
name = "clap"
version = "4.5.18"
version = "4.5.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0956a43b323ac1afaffc053ed5c4b7c1f1800bacd1683c353aabbb752515dd3"
checksum = "b97f376d85a664d5837dbae44bf546e6477a679ff6610010f17276f686d867e8"
dependencies = [
"clap_builder",
"clap_derive",
@@ -707,9 +707,9 @@ dependencies = [
[[package]]
name = "clap_builder"
version = "4.5.18"
version = "4.5.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4d72166dd41634086d5803a47eb71ae740e61d84709c36f3c34110173db3961b"
checksum = "19bc80abd44e4bed93ca373a0704ccbd1b710dc5749406201bb018272808dc54"
dependencies = [
"anstream",
"anstyle",
@@ -1729,7 +1729,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e310b3a6b5907f99202fcdb4960ff45b93735d7c7d96b760fcff8db2dc0e103d"
dependencies = [
"cfg-if",
"windows-targets 0.52.5",
"windows-targets 0.48.5",
]
[[package]]

106
docs/SETUP_DEV.md Normal file
View File

@@ -0,0 +1,106 @@
# Setup development environment
## Backend
To build the backend, you will need to install:
* Rust: https://www.rust-lang.org/
* An IDE with Rust support. I would definitly recommend [RustRover](https://www.jetbrains.com/rust/) (the tool from IntelliJ).
Check if your environment is working using the following command:
```bash
cargo fmt && cargo clippy && cargo run -- --help
```
For development, the following flags might prove being useful:
* `--unsecure-disable-login`: Disable authentication on all web API endpoints
* `--hostname`: Change public server hostname, if you want to expose your test instance to network device, such as an ESP32
## Custom consumption
Same requirements as for the backend. This tool spawns a gui that allows to set arbitrary consumption values:
![Custom consumption](img/custom_consumption.png)
To use it, first launch this tool:
```bash
cd custom_consumption
cargo run
```
Set a custom value to force file creation (in the UI).
Then launch central backend (in another terminal):
```bash
cd central_backend
cargo fmt && cargo clippy && RUST_LOG=debug cargo run -- file
```
## Central frontend
The frontend has been built using [NodeJS](https://nodejs.org/en), [Vite](https://vite.dev/) and [MUI](https://mui.com/).
Launch it using this command:
```bash
cd central_frontend
npm run dev
```
## Python device
This component has been built using ... Python. Waw!
You will need to install this dependency, first:
```bash
apt install python3-jwt
```
Run the client:
```bash
cd python_device
python3 -m src.main
# Get CLI help
python3 -m src.main --help
```
Reformat code:
```bash
black src/*.py
```
## ESP32 device
The ESP32 device is in reality a [Wt32-Eth01](https://en.wireless-tag.com/product-item-2.html) device. Use the following mapping to setup dev env:
![ESP mapping](img/esp_mapping.png)
You can use a [CP2102](https://fr.aliexpress.com/item/4000120687489.html) to flash the ESP32.
I recommend to use VSCode with the following extensions:
* [ESP-IDF](https://marketplace.visualstudio.com/items?itemName=espressif.esp-idf-extension)
* [C/C++](https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools)
* [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode)
To build the project, use this command (in an ESP-IDF terminal):
```bash
idf.py build
```
To flash the ESP32, use this one:
```bash
idf.py flash
```
To capture logs from device, use either `cu` or the following command:
```
idf.py monitor
```

48
docs/SETUP_PROD.md Normal file
View File

@@ -0,0 +1,48 @@
# Configure project for production
## Create production build
### Central
The production release of central backend and frontend can be realised on a computer which has NodeJS and Rust installed by executing the following command at the root of the project:
```bash
make
```
The backend will be available at this location:
```
central_backend/target/release/central_backend
```
### Python device
The Python device isn't production ready yet.
### ESP32 device
#### Flashing the device directly
Use the following commands to flash a device (inside ESP-IDF environnment):
```bash
idf.py build
idf.py flash
```
#### Getting an OTA update
Use the following command to build an OTA update:
```bash
idf.py build
```
The OTA update is then located in `build/main.bin`
## Pre-requisites
* A server running a recent Linux (Debian / Ubuntu preferred) with `central` as hostname
* DHCP configured on the network
## Configure server
TODO

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

BIN
docs/img/esp_mapping.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

View File

@@ -49,6 +49,12 @@
"regex": "c",
"stdlib.h": "c",
"secure_api.h": "c",
"jwt.h": "c"
"jwt.h": "c",
"sync_response.h": "c",
"gpio.h": "c",
"esp_system.h": "c",
"relays.h": "c",
"esp_app_desc.h": "c",
"ota.h": "c"
}
}

View File

@@ -1,3 +1,18 @@
# ESP32 device
ESP32 client device, using `W32-ETH01` device
## Some commands
Create a new firmware build:
```bash
idf.py build
```
Upload firmware to central backend, in dev mode:
```bash
curl -k -X POST https://localhost:8443/web_api/ota/Wt32-Eth01/$(cat version.txt) --form firmware="@build/main.bin"
curl -k -X POST https://localhost:8443/web_api/ota/set_desired_version --header "Content-Type: application/json" --data "{\"platform\": \"Wt32-Eth01\", \"version\": \"$(cat version.txt)\"}"
```

View File

@@ -0,0 +1,5 @@
#!/bin/sh
idf.py build && \
curl -k -X POST https://localhost:8443/web_api/ota/Wt32-Eth01/$(cat version.txt) --form firmware="@build/main.bin" && \
curl -k -X POST https://localhost:8443/web_api/ota/set_desired_version --header "Content-Type: application/json" --data "{\"platform\": \"Wt32-Eth01\", \"version\": \"$(cat version.txt)\"}"

Binary file not shown.

View File

@@ -1,4 +1,4 @@
idf_component_register(SRCS "jwt.c" "secure_api.c" "http_client.c" "ethernet.c" "unsecure_api.c" "system.c" "crypto.c" "random.c" "storage.c" "main.c"
idf_component_register(SRCS "ota.c" "relays.c" "sync_response.c" "jwt.c" "secure_api.c" "http_client.c" "ethernet.c" "unsecure_api.c" "system.c" "crypto.c" "random.c" "storage.c" "main.c"
"dev_name.c"
INCLUDE_DIRS ".")

View File

@@ -5,16 +5,6 @@
*/
#define DEV_REFERENCE "Wt32-Eth01"
/**
* Device version
*/
#define DEV_VERSION "0.0.1"
/**
* Device max number of relays
*/
#define DEV_MAX_RELAYS 1
/**
* Backend unsecure API URL
*/
@@ -44,3 +34,13 @@
* Secure origin len
*/
#define SEC_ORIG_LEN 255
/**
* Interval of time (in seconds) between two synchronisations
*/
#define SYNC_TIME_INTERVAL 5
/**
* OTA download timeout (in milliseconds)
*/
#define OTA_REC_TIMEOUT 15000

View File

@@ -29,12 +29,12 @@ static void seed_ctr_drbg_context(mbedtls_entropy_context *entropy, mbedtls_ctr_
mbedtls_entropy_init(entropy);
mbedtls_ctr_drbg_init(ctr_drbg);
ESP_LOGI(TAG, "Seed Mbedtls\n");
ESP_LOGI(TAG, "Seed Mbedtls");
if ((ret = mbedtls_ctr_drbg_seed(ctr_drbg, mbedtls_entropy_func, entropy,
(const unsigned char *)pers,
strlen(pers))) != 0)
{
ESP_LOGE(TAG, " failed\n ! mbedtls_ctr_drbg_seed returned %d\n", ret);
ESP_LOGE(TAG, " failed\n ! mbedtls_ctr_drbg_seed returned %d", ret);
reboot();
}
}
@@ -54,7 +54,7 @@ bool crypto_gen_priv_key()
mbedtls_ctr_drbg_context ctr_drbg;
seed_ctr_drbg_context(&entropy, &ctr_drbg);
ESP_LOGI(TAG, "PK info from type\n");
ESP_LOGI(TAG, "PK info from type");
if ((ret = mbedtls_pk_setup(&key, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY))) != 0)
{
ESP_LOGE(TAG, " failed\n ! mbedtls_pk_setup returned -0x%04x", (unsigned int)-ret);
@@ -62,7 +62,7 @@ bool crypto_gen_priv_key()
}
// Generate private key
ESP_LOGI(TAG, "Generate private key\n");
ESP_LOGI(TAG, "Generate private key");
ret = mbedtls_ecp_gen_key(ECPARAMS,
mbedtls_pk_ec(key),
mbedtls_ctr_drbg_random, &ctr_drbg);
@@ -74,7 +74,7 @@ bool crypto_gen_priv_key()
}
// Export private key
ESP_LOGI(TAG, "Export private key\n");
ESP_LOGI(TAG, "Export private key");
unsigned char *key_buff = malloc(PRV_KEY_DER_MAX_BYTES);
if ((ret = mbedtls_pk_write_key_der(&key, key_buff, PRV_KEY_DER_MAX_BYTES)) < 1)
{
@@ -108,7 +108,7 @@ void crypto_print_priv_key()
mbedtls_ctr_drbg_context ctr_drbg;
seed_ctr_drbg_context(&entropy, &ctr_drbg);
ESP_LOGI(TAG, "Parse private key (len = %d)\n", key_len);
ESP_LOGI(TAG, "Parse private key (len = %d)", key_len);
if ((ret = mbedtls_pk_parse_key(&key, key_buff, key_len, NULL, 0, mbedtls_ctr_drbg_random, &ctr_drbg)) != 0)
{
ESP_LOGE(TAG, " failed\n ! mbedtls_pk_parse_key returned -0x%04x",
@@ -117,7 +117,7 @@ void crypto_print_priv_key()
}
free(key_buff);
ESP_LOGI(TAG, "Show private key\n");
ESP_LOGI(TAG, "Show private key");
unsigned char *out = malloc(16000);
memset(out, 0, 16000);
if ((ret = mbedtls_pk_write_key_pem(&key, out, 16000)) != 0)
@@ -153,7 +153,7 @@ static bool crypto_get_priv_key_mpi(mbedtls_mpi *dst)
mbedtls_ctr_drbg_context ctr_drbg;
seed_ctr_drbg_context(&entropy, &ctr_drbg);
ESP_LOGI(TAG, "Parse private key (len = %d)\n", key_len);
ESP_LOGI(TAG, "Parse private key (len = %d)", key_len);
if ((ret = mbedtls_pk_parse_key(&key, key_buff, key_len, NULL, 0, mbedtls_ctr_drbg_random, &ctr_drbg)) != 0)
{
ESP_LOGE(TAG, " failed\n ! mbedtls_pk_parse_key returned -0x%04x",
@@ -190,7 +190,7 @@ char *crypto_get_csr()
mbedtls_ctr_drbg_context ctr_drbg;
seed_ctr_drbg_context(&entropy, &ctr_drbg);
ESP_LOGI(TAG, "Parse private key (len = %d)\n", key_len);
ESP_LOGI(TAG, "Parse private key (len = %d)", key_len);
if ((ret = mbedtls_pk_parse_key(&key, key_buff, key_len, NULL, 0, mbedtls_ctr_drbg_random, &ctr_drbg)) != 0)
{
ESP_LOGE(TAG, " failed\n ! mbedtls_pk_parse_key returned -0x%04x",
@@ -214,7 +214,7 @@ char *crypto_get_csr()
reboot();
}
ESP_LOGI(TAG, "Sign CSR with private key\n");
ESP_LOGI(TAG, "Sign CSR with private key");
mbedtls_x509write_csr_set_key(&req, &key);
char *csr = malloc(4096);

View File

@@ -33,7 +33,7 @@ char *dev_name()
char *dev = malloc(len + strlen(DEV_PREFIX) + 1);
if (dev == NULL)
{
ESP_LOGE(TAG, "Failed to allocate memory to store dev name!\n");
ESP_LOGE(TAG, "Failed to allocate memory to store dev name!");
return NULL;
}

View File

@@ -84,8 +84,8 @@ void ethernet_init()
eth_esp32_emac_config_t mac_config = ETH_ESP32_EMAC_DEFAULT_CONFIG();
mac_config.clock_config.rmii.clock_mode = EMAC_CLK_EXT_IN;
mac_config.clock_config.rmii.clock_gpio = EMAC_CLK_IN_GPIO;
mac_config.smi_mdc_gpio_num = GPIO_NUM_23;
mac_config.smi_mdio_gpio_num = GPIO_NUM_18;
mac_config.smi_gpio.mdc_num = GPIO_NUM_23;
mac_config.smi_gpio.mdio_num = GPIO_NUM_18;
eth_mac_config_t eth_mac_config = ETH_MAC_DEFAULT_CONFIG();
eth_mac_config.sw_reset_timeout_ms = 1000;

View File

@@ -1,6 +1,7 @@
#include <stdio.h>
#include "esp_system.h"
#include "esp_log.h"
#include "esp_app_desc.h"
#include "dev_name.h"
#include "storage.h"
@@ -10,54 +11,60 @@
#include "secure_api.h"
#include "ethernet.h"
#include "constants.h"
#include "relays.h"
#include "ota.h"
static const char *TAG = "main";
void app_main(void)
{
esp_log_level_set("*", ESP_LOG_VERBOSE);
esp_log_level_set("*", ESP_LOG_INFO);
system_show_free_memory();
ESP_LOGI(TAG, "SolarEnergy WT32-ETH01 device");
ESP_LOGI(TAG, "SolarEnergy WT32-ETH01 device version %s", esp_app_get_description()->version);
// Turn off all relays
relays_turn_off_all();
relays_setup();
// Initialize storage
if (storage_init() == false)
{
ESP_LOGE(TAG, "Failed to init storage!\n");
ESP_LOGE(TAG, "Failed to init storage!");
reboot();
}
// Give a name to the device
if (dev_generate_name())
{
ESP_LOGI(TAG, "Generated a new device name\n");
ESP_LOGI(TAG, "Generated a new device name");
}
char *name = dev_name();
ESP_LOGI(TAG, "Dev name: %s\n", name);
ESP_LOGI(TAG, "Dev name: %s", name);
free(name);
// Generate private key, if needed
if (crypto_gen_priv_key())
{
ESP_LOGI(TAG, "Generated device private key!\n");
ESP_LOGI(TAG, "Generated device private key!");
}
ESP_LOGI(TAG, "Device private key:\n");
ESP_LOGI(TAG, "Device private key:");
crypto_print_priv_key();
// Show current private key
char *csr = crypto_get_csr();
ESP_LOGI(TAG, "Current CSR:\n%s\n", csr);
ESP_LOGI(TAG, "Current CSR:\n%s", csr);
free(csr);
// Initialize network stack
ESP_LOGI(TAG, "Initialize network\n");
ESP_LOGI(TAG, "Initialize network");
ethernet_init();
ethernet_wait_for_network();
// Get if secure origin endpoint is known
ESP_LOGI(TAG, "Check secure origin\n");
ESP_LOGI(TAG, "Check secure origin");
if (storage_get_secure_origin(NULL) == 0)
{
char *sec_ori = unsecure_api_get_secure_origin();
@@ -71,7 +78,7 @@ void app_main(void)
}
// Print secure origin endpoint for debugging purposes
ESP_LOGI(TAG, "Get secure origin\n");
ESP_LOGI(TAG, "Get secure origin");
char *sec_ori = calloc(SEC_ORIG_LEN, 1);
assert(storage_get_secure_origin(sec_ori) > 0);
ESP_LOGI(TAG, "Current secure origin: %s", sec_ori);
@@ -104,7 +111,7 @@ void app_main(void)
// Check current device enrollment status
ESP_LOGI(TAG, "Check enrollment status");
enum DevEnrollmentStatus status = secure_api_get_device_enrollment_status();
ESP_LOGI(TAG, "Current enrollment status: %d\n", status);
ESP_LOGI(TAG, "Current enrollment status: %d", status);
switch (status)
{
@@ -166,23 +173,74 @@ void app_main(void)
// Main loop
ESP_LOGI(TAG, "Starting main loop");
secure_api_report_log_message(Info, "Starting program main loop");
// TODO : implement more properly
size_t fails = 0;
while (true)
{
if (!secure_api_sync_device())
sync_response *res = secure_api_sync_device();
if (!res)
{
ESP_LOGE(TAG, "Failed to synchronise device!");
fails += 1;
ESP_LOGE(TAG, "Failed to synchronise device! (number=%d)", fails);
// Safely turn off all relays after a given number of failures
if (fails > 5)
{
ESP_LOGE(TAG, "Many failures, will stop all relays...");
relays_turn_off_all();
}
// Restart the card after too much failures
if (fails > 10)
{
ESP_LOGE(TAG, "Too many failures, will try to reboot in 3 secs...");
system_sleep(3);
reboot();
}
system_sleep(SYNC_TIME_INTERVAL);
continue;
}
fails = 0;
sync_response_print(res);
// Check for firmware update
if (res->available_update)
{
ESP_LOGI(TAG, "Will perform system upgrade to version %s!", res->available_update);
relays_turn_off_all();
secure_api_report_log_message(Info, "Device is starting the OTA procedure...");
if (ota_perform_update(res->available_update))
{
ESP_LOGI(TAG, "OTA update succesfully executed, will reboot...");
secure_api_report_log_message(Info, "Device successfully updated!");
}
else
{
ESP_LOGI(TAG, "Successfully synchronised device!");
ESP_LOGE(TAG, "OTA update failed! Will reboot...");
secure_api_report_log_message(Error, "Device update failed!");
}
system_sleep(10);
secure_api_report_log_message(Info, "Device will restart after OTA procedure...");
system_sleep(SYNC_TIME_INTERVAL);
reboot();
}
system_sleep(120);
// Update relays configuration
for (size_t i = 0; i < relays_count(); i++)
{
relays_set(i, sync_response_is_relay_on(res, i));
}
sync_response_free(res);
system_sleep(SYNC_TIME_INTERVAL);
}
reboot();
}

232
esp32_device/main/ota.c Normal file
View File

@@ -0,0 +1,232 @@
#include "esp_log.h"
#include "esp_partition.h"
#include "esp_ota_ops.h"
#include "esp_http_client.h"
#include "esp_app_format.h"
#include "constants.h"
#include "ota.h"
#include "storage.h"
#include "secure_api.h"
#include <string.h>
const char *TAG = "ota";
#define BUFF_SIZE 1024
static void http_cleanup(esp_http_client_handle_t client)
{
esp_http_client_close(client);
esp_http_client_cleanup(client);
}
bool ota_perform_update(const char *version)
{
const esp_partition_t *configured = esp_ota_get_boot_partition();
const esp_partition_t *running = esp_ota_get_running_partition();
if (configured != running)
{
ESP_LOGW(TAG, "Configured OTA boot partition at offset 0x%08" PRIx32 ", but running from offset 0x%08" PRIx32,
configured->address, running->address);
ESP_LOGW(TAG, "(This can happen if either the OTA boot data or preferred boot image become corrupted somehow.)");
}
ESP_LOGI(TAG, "Running partition type %d subtype %d (offset 0x%08" PRIx32 ")",
running->type, running->subtype, running->address);
// Determine firmware download URL
char *update_url = calloc(256, 1);
assert(update_url != NULL);
assert(storage_get_secure_origin(update_url) > 0);
strcat(update_url, "/devices_api/ota/Wt32-Eth01/");
strcat(update_url, version);
ESP_LOGI(TAG, "Firmware URL: %s", update_url);
char *root_ca = calloc(1, ROOT_CA_MAX_BYTES);
assert(root_ca);
assert(storage_get_root_ca(root_ca) > 0);
esp_http_client_config_t config = {
.url = update_url,
.cert_pem = root_ca,
.timeout_ms = OTA_REC_TIMEOUT,
.keep_alive_enable = true,
};
esp_http_client_handle_t client = esp_http_client_init(&config);
if (client == NULL)
{
ESP_LOGE(TAG, "Failed to initialise HTTP connection");
free(update_url);
free(root_ca);
return false;
}
int err = esp_http_client_open(client, 0);
free(update_url);
free(root_ca);
if (err != ESP_OK)
{
ESP_LOGE(TAG, "Failed to open HTTP connection: %s", esp_err_to_name(err));
esp_http_client_cleanup(client);
return false;
}
esp_http_client_fetch_headers(client);
const esp_partition_t *update_partition = esp_ota_get_next_update_partition(NULL);
assert(update_partition != NULL);
ESP_LOGI(TAG, "Writing to partition subtype %d at offset 0x%" PRIx32,
update_partition->subtype, update_partition->address);
// OTA update loop
int binary_file_length = 0;
esp_ota_handle_t update_handle = 0;
/*deal with all receive packet*/
bool image_header_was_checked = false;
char *ota_write_data = calloc(BUFF_SIZE + 1, 1);
while (1)
{
int data_read = esp_http_client_read(client, ota_write_data, BUFF_SIZE);
if (data_read < 0)
{
ESP_LOGE(TAG, "Error: SSL data read error");
http_cleanup(client);
free(ota_write_data);
return false;
}
if (data_read == 0)
{
/*
* As esp_http_client_read never returns negative error code, we rely on
* `errno` to check for underlying transport connectivity closure if any
*/
if (errno == ECONNRESET || errno == ENOTCONN)
{
ESP_LOGE(TAG, "Connection closed, errno = %d", errno);
break;
}
if (esp_http_client_is_complete_data_received(client) == true)
{
ESP_LOGI(TAG, "Connection closed");
break;
}
// No data received yet
continue;
}
if (image_header_was_checked == false)
{
esp_app_desc_t new_app_info;
if (data_read > sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t) + sizeof(esp_app_desc_t))
{
// check current version with downloading
memcpy(&new_app_info, &ota_write_data[sizeof(esp_image_header_t) + sizeof(esp_image_segment_header_t)], sizeof(esp_app_desc_t));
ESP_LOGI(TAG, "New firmware version: %s", new_app_info.version);
esp_app_desc_t running_app_info;
if (esp_ota_get_partition_description(running, &running_app_info) == ESP_OK)
{
ESP_LOGI(TAG, "Running firmware version: %s", running_app_info.version);
}
const esp_partition_t *last_invalid_app = esp_ota_get_last_invalid_partition();
esp_app_desc_t invalid_app_info;
if (esp_ota_get_partition_description(last_invalid_app, &invalid_app_info) == ESP_OK)
{
ESP_LOGI(TAG, "Last invalid firmware version: %s", invalid_app_info.version);
}
// check current version with last invalid partition
if (last_invalid_app != NULL)
{
if (memcmp(invalid_app_info.version, new_app_info.version, sizeof(new_app_info.version)) == 0)
{
ESP_LOGW(TAG, "New version is the same as invalid version.");
ESP_LOGW(TAG, "Previously, there was an attempt to launch the firmware with %s version, but it failed.", invalid_app_info.version);
ESP_LOGW(TAG, "The firmware has been rolled back to the previous version.");
http_cleanup(client);
free(ota_write_data);
secure_api_report_log_message(Error, "New version is the same as last invalid version. Could not perform update!");
return false;
}
}
image_header_was_checked = true;
err = esp_ota_begin(update_partition, OTA_WITH_SEQUENTIAL_WRITES, &update_handle);
if (err != ESP_OK)
{
ESP_LOGE(TAG, "esp_ota_begin failed (%s)", esp_err_to_name(err));
http_cleanup(client);
free(ota_write_data);
esp_ota_abort(update_handle);
return false;
}
ESP_LOGI(TAG, "esp_ota_begin succeeded");
}
else
{
ESP_LOGE(TAG, "received package is not fit len");
http_cleanup(client);
free(ota_write_data);
esp_ota_abort(update_handle);
return false;
}
}
err = esp_ota_write(update_handle, (const void *)ota_write_data, data_read);
if (err != ESP_OK)
{
http_cleanup(client);
free(ota_write_data);
esp_ota_abort(update_handle);
return false;
}
binary_file_length += data_read;
ESP_LOGD(TAG, "Written image length %d", binary_file_length);
}
free(ota_write_data);
ESP_LOGI(TAG, "Total Write binary data length: %d", binary_file_length);
if (esp_http_client_is_complete_data_received(client) != true)
{
ESP_LOGE(TAG, "Error in receiving complete file");
http_cleanup(client);
esp_ota_abort(update_handle);
return false;
}
err = esp_ota_end(update_handle);
if (err != ESP_OK)
{
if (err == ESP_ERR_OTA_VALIDATE_FAILED)
{
ESP_LOGE(TAG, "Image validation failed, image is corrupted");
}
else
{
ESP_LOGE(TAG, "esp_ota_end failed (%s)!", esp_err_to_name(err));
}
http_cleanup(client);
return false;
}
err = esp_ota_set_boot_partition(update_partition);
if (err != ESP_OK)
{
ESP_LOGE(TAG, "esp_ota_set_boot_partition failed (%s)!", esp_err_to_name(err));
http_cleanup(client);
return false;
}
ESP_LOGI(TAG, "End of OTA procedure!");
return true;
}

24
esp32_device/main/ota.h Normal file
View File

@@ -0,0 +1,24 @@
/**
* OTA functions
*/
#pragma once
#include <stddef.h>
#include <stdbool.h>
#ifdef __cplusplus
extern "C"
{
#endif
/**
* Update device to a desired version
*
* Returns TRUE in case of success / FALSE otherwise
*/
bool ota_perform_update(const char *version);
#ifdef __cplusplus
}
#endif

View File

@@ -0,0 +1,63 @@
#include <driver/gpio.h>
#include "esp_log.h"
#include "relays.h"
#include "constants.h"
static const char *TAG = "relays";
/**
* Device relays GPIO ids
*/
static int DEVICE_GPIO_IDS[3] = {4, 14, 15};
int relays_count()
{
return sizeof(DEVICE_GPIO_IDS) / sizeof(int);
}
void relays_setup()
{
int pin_bit_mask = 0;
for (size_t i = 0; i < relays_count(); i++)
{
pin_bit_mask |= 1ULL << DEVICE_GPIO_IDS[i];
}
// zero-initialize the config structure.
gpio_config_t io_conf = {};
// disable interrupt
io_conf.intr_type = GPIO_INTR_DISABLE;
// set as output mode
io_conf.mode = GPIO_MODE_OUTPUT;
// bit mask of the pins that you want to set,e.g.GPIO18/19
io_conf.pin_bit_mask = pin_bit_mask;
// disable pull-down mode
io_conf.pull_down_en = 0;
// disable pull-up mode
io_conf.pull_up_en = 0;
// configure GPIO with the given settings
gpio_config(&io_conf);
}
void relays_turn_off_all()
{
ESP_LOGI(TAG, "Turning off all relays...");
for (size_t i = 0; i < relays_count(); i++)
{
relays_set(i, false);
}
}
void relays_set(int number, bool is_on)
{
size_t gpio_id = DEVICE_GPIO_IDS[number];
ESP_LOGI(TAG, "Set relay %d (gpio %d) to %s", number, gpio_id, is_on ? "on" : "off");
int res = gpio_set_level(gpio_id, is_on ? 0 : 1);
if (res != ESP_OK)
{
ESP_LOGE(TAG, "Failed to toggle GPIO %d : %d", gpio_id, res);
}
}

View File

@@ -0,0 +1,36 @@
/**
* Relays management
*/
#pragma once
#include <stddef.h>
#ifdef __cplusplus
extern "C"
{
#endif
/**
* Get the max number of relays
*/
int relays_count();
/**
* Configure the relays
*/
void relays_setup();
/**
* Turn off all relays
*/
void relays_turn_off_all();
/**
* Turn on / off a relay
*/
void relays_set(int number, bool is_on);
#ifdef __cplusplus
}
#endif

View File

@@ -11,8 +11,10 @@
#include "storage.h"
#include "http_client.h"
#include "jwt.h"
#include "relays.h"
#include "esp_log.h"
#include "esp_app_desc.h"
static const char *TAG = "secure_api";
@@ -117,12 +119,14 @@ fail:
*/
static cJSON *genDevInfo()
{
const esp_app_desc_t *desc = esp_app_get_description();
cJSON *json = cJSON_CreateObject();
if (!json)
return NULL;
cJSON_AddStringToObject(json, "reference", DEV_REFERENCE);
cJSON_AddStringToObject(json, "version", DEV_VERSION);
cJSON_AddNumberToObject(json, "max_relays", DEV_MAX_RELAYS);
cJSON_AddStringToObject(json, "version", desc->version);
cJSON_AddNumberToObject(json, "max_relays", relays_count());
return json;
}
@@ -148,16 +152,16 @@ int secure_api_enroll_device()
free(csr);
char *body = cJSON_PrintUnformatted(obj);
cJSON_Delete(obj);
if (!body)
{
ESP_LOGE(TAG, "Failed to generate JSON body!");
cJSON_Delete(obj);
return 1;
}
char *res = process_secure_request("/devices_api/mgmt/enroll", body);
cJSON_Delete(obj);
free(body);
if (res == NULL)
@@ -195,7 +199,78 @@ char *secure_api_get_dev_certificate()
return res;
}
void *secure_api_sync_device()
void secure_api_report_log_message(enum LogMessageSeverity severity, const char *msg)
{
// Prepare signed payload
cJSON *obj = cJSON_CreateObject();
if (!obj)
{
ESP_LOGE(TAG, "Failed allocate memory to store JSON object!");
return;
}
char *severity_s;
switch (severity)
{
case Info:
severity_s = "Info";
break;
case Warn:
severity_s = "Warn";
break;
case Error:
severity_s = "Error";
break;
default:
severity_s = "Debug";
break;
}
cJSON_AddStringToObject(obj, "severity", severity_s);
cJSON_AddStringToObject(obj, "message", msg);
char *payload = jwt_gen(obj);
cJSON_Delete(obj);
if (!payload)
{
ESP_LOGE(TAG, "Failed to build log report request!");
return;
}
// Prepare request body
cJSON *json_body = cJSON_CreateObject();
if (!json_body)
{
ESP_LOGE(TAG, "Failed to allocated memory to store log report request body!");
free(payload);
return;
}
cJSON_AddStringToObject(json_body, "payload", payload);
free(payload);
char *body = cJSON_PrintUnformatted(json_body);
cJSON_Delete(json_body);
if (!body)
{
ESP_LOGE(TAG, "Failed to allocated memory to store encoded log report request body!");
return;
}
// Send request
char *res = process_secure_request("/devices_api/logging/record", body);
free(body);
if (!res)
{
ESP_LOGE(TAG, "Log reporting failed!");
}
free(res);
}
sync_response *secure_api_sync_device()
{
cJSON *obj = cJSON_CreateObject();
if (!obj)
@@ -215,10 +290,54 @@ void *secure_api_sync_device()
return NULL;
}
printf("JWT: %s\n", encoded_req);
// Prepare request body
cJSON *json_body = cJSON_CreateObject();
if (!json_body)
{
ESP_LOGE(TAG, "Failed to allocated memory to store sync request body!");
free(encoded_req);
return NULL;
}
cJSON_AddStringToObject(json_body, "payload", encoded_req);
free(encoded_req);
// TODO : replace
printf("here implement sync device logic\n");
char *body = cJSON_PrintUnformatted(json_body);
cJSON_Delete(json_body);
if (!body)
{
ESP_LOGE(TAG, "Failed to allocated memory to store encoded sync request body!");
return NULL;
}
// Send request
char *res = process_secure_request("/devices_api/mgmt/sync", body);
free(body);
if (res == NULL)
{
ESP_LOGE(TAG, "Sync request failed!");
return NULL;
}
// Parse response
cJSON *states = cJSON_Parse(res);
free(res);
if (!states)
{
ESP_LOGE(TAG, "Failed to decode sync response from server!");
return NULL;
}
sync_response *sync_res = sync_response_parse(states);
cJSON_Delete(states);
if (!sync_res)
{
ESP_LOGE(TAG, "Failed to parse sync response from server!");
return NULL;
}
return sync_res;
}

View File

@@ -2,6 +2,11 @@
* Secure API functions
*/
#include <stddef.h>
#include <stdbool.h>
#include "sync_response.h"
#pragma once
#ifdef __cplusplus
@@ -24,6 +29,17 @@ extern "C"
DevEnrollValidated = 3,
};
/**
* Log message severity
*/
enum LogMessageSeverity
{
Debug = 0,
Info,
Warn,
Error
};
/**
* Get current device enrollment status
*/
@@ -40,12 +56,17 @@ extern "C"
*/
char *secure_api_get_dev_certificate();
/**
* Report log message to backend
*/
void secure_api_report_log_message(enum LogMessageSeverity severity, const char *msg);
/**
* Synchronise device with central backend
*
* Returns NULL in case of failure
*/
void *secure_api_sync_device();
sync_response *secure_api_sync_device();
#ifdef __cplusplus
}

View File

@@ -20,7 +20,7 @@ bool storage_init()
esp_err_t err = nvs_flash_init();
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND)
{
ESP_LOGI(TAG, "Need to reset storage\n");
ESP_LOGI(TAG, "Need to reset storage");
// NVS partition was truncated and needs to be erased
// Retry nvs_flash_init

View File

@@ -0,0 +1,96 @@
#include "sync_response.h"
#include <stdlib.h>
#include <string.h>
#include <esp_log.h>
const static char *TAG = "sync_response";
sync_response *sync_response_parse(cJSON *res)
{
// Parse relays information
cJSON *relays_json = cJSON_GetObjectItem(res, "relays");
if (relays_json == NULL)
{
ESP_LOGE(TAG, "Missing relays status in sync response!");
return NULL;
}
int relays_size = cJSON_GetArraySize(relays_json);
sync_response *sync_res = calloc(1, sizeof(sync_response) + relays_size * sizeof(bool));
if (!sync_res)
{
ESP_LOGE(TAG, "Failed to allocate memory to store synchronization response!");
return NULL;
}
sync_res->len = relays_size;
for (int i = 0; i < sync_res->len; i++)
{
sync_res->relays[i] = false;
cJSON *item = cJSON_GetArrayItem(relays_json, i);
assert(item != NULL);
cJSON *enabled = cJSON_GetObjectItem(item, "enabled");
if (enabled == NULL)
{
ESP_LOGE(TAG, "At least a relay is missing the enabled field. Assuming false.");
continue;
}
if (cJSON_IsTrue(enabled))
{
sync_res->relays[i] = true;
}
}
// Parse firmware update information
cJSON *update = cJSON_GetObjectItem(res, "available_update");
if (update != NULL)
{
char *val = cJSON_GetStringValue(update);
sync_res->available_update = val != NULL ? strdup(val) : NULL;
}
return sync_res;
}
void sync_response_print(sync_response *res)
{
ESP_LOGI(TAG, " === sync response begin === ");
if (res->available_update != NULL)
{
ESP_LOGI(TAG, "> AVAILABLE UPDATE! Version %s", res->available_update);
}
ESP_LOGI(TAG, "# of relays: %d", res->len);
for (size_t i = 0; i < res->len; i++)
ESP_LOGI(TAG, "Relay[%d]=%s", i, res->relays[i] ? "ON" : "off");
ESP_LOGI(TAG, " === sync response end === ");
}
void sync_response_free(sync_response *res)
{
if (res == NULL)
return;
if (res->available_update != NULL)
free(res->available_update);
free(res);
}
bool sync_response_is_relay_on(sync_response *res, int relay_number)
{
if (res->len <= relay_number)
{
ESP_LOGW(TAG, "Requested state of an unconfigured relay (%d). Defaulting to off.", relay_number);
return false;
}
return res->relays[relay_number];
}

View File

@@ -0,0 +1,45 @@
/**
* Synchronisation response
*/
#pragma once
#include <stddef.h>
#include <stdbool.h>
#include <cJSON.h>
#ifdef __cplusplus
extern "C"
{
#endif
typedef struct sync_response
{
size_t len;
char *available_update;
bool relays[];
} sync_response;
/**
* Decode synchronize response from server
*/
sync_response *sync_response_parse(cJSON *res);
/**
* Print synchronize reponse content
*/
void sync_response_print(sync_response *res);
/**
* Free memory allocated for synchronize response
*/
void sync_response_free(sync_response *res);
/**
* Check the desired status of a relay
*/
bool sync_response_is_relay_on(sync_response *res, int relay_number);
#ifdef __cplusplus
}
#endif

View File

@@ -1,6 +1,6 @@
#
# Automatically generated file. DO NOT EDIT.
# Espressif IoT Development Framework (ESP-IDF) 5.2.2 Project Configuration
# Espressif IoT Development Framework (ESP-IDF) 5.3.1 Project Configuration
#
CONFIG_SOC_BROWNOUT_RESET_SUPPORTED="Not determined"
CONFIG_SOC_TWAI_BRP_DIV_SUPPORTED="Not determined"
@@ -14,6 +14,7 @@ CONFIG_SOC_GPTIMER_SUPPORTED=y
CONFIG_SOC_SDMMC_HOST_SUPPORTED=y
CONFIG_SOC_BT_SUPPORTED=y
CONFIG_SOC_PCNT_SUPPORTED=y
CONFIG_SOC_PHY_SUPPORTED=y
CONFIG_SOC_WIFI_SUPPORTED=y
CONFIG_SOC_SDIO_SLAVE_SUPPORTED=y
CONFIG_SOC_TWAI_SUPPORTED=y
@@ -43,6 +44,11 @@ CONFIG_SOC_CLK_TREE_SUPPORTED=y
CONFIG_SOC_MPU_SUPPORTED=y
CONFIG_SOC_WDT_SUPPORTED=y
CONFIG_SOC_SPI_FLASH_SUPPORTED=y
CONFIG_SOC_RNG_SUPPORTED=y
CONFIG_SOC_LIGHT_SLEEP_SUPPORTED=y
CONFIG_SOC_DEEP_SLEEP_SUPPORTED=y
CONFIG_SOC_LP_PERIPH_SHARE_INTERRUPT=y
CONFIG_SOC_PM_SUPPORTED=y
CONFIG_SOC_DPORT_WORKAROUND_DIS_INTERRUPT_LVL=5
CONFIG_SOC_XTAL_SUPPORT_26M=y
CONFIG_SOC_XTAL_SUPPORT_40M=y
@@ -84,7 +90,9 @@ CONFIG_SOC_GPIO_IN_RANGE_MAX=39
CONFIG_SOC_GPIO_OUT_RANGE_MAX=33
CONFIG_SOC_GPIO_VALID_DIGITAL_IO_PAD_MASK=0xEF0FEA
CONFIG_SOC_GPIO_CLOCKOUT_BY_IO_MUX=y
CONFIG_SOC_GPIO_CLOCKOUT_CHANNEL_NUM=3
CONFIG_SOC_I2C_NUM=2
CONFIG_SOC_HP_I2C_NUM=2
CONFIG_SOC_I2C_FIFO_LEN=32
CONFIG_SOC_I2C_CMD_REG_NUM=16
CONFIG_SOC_I2C_SUPPORT_SLAVE=y
@@ -164,9 +172,9 @@ CONFIG_SOC_TIMER_GROUP_TIMERS_PER_GROUP=2
CONFIG_SOC_TIMER_GROUP_COUNTER_BIT_WIDTH=64
CONFIG_SOC_TIMER_GROUP_TOTAL_TIMERS=4
CONFIG_SOC_TIMER_GROUP_SUPPORT_APB=y
CONFIG_SOC_TOUCH_VERSION_1=y
CONFIG_SOC_TOUCH_SENSOR_VERSION=1
CONFIG_SOC_TOUCH_SENSOR_NUM=10
CONFIG_SOC_TOUCH_PAD_MEASURE_WAIT_MAX=0xFF
CONFIG_SOC_TOUCH_SAMPLE_CFG_NUM=1
CONFIG_SOC_TWAI_CONTROLLER_NUM=1
CONFIG_SOC_TWAI_BRP_MIN=2
CONFIG_SOC_TWAI_CLK_SUPPORT_APB=y
@@ -222,8 +230,10 @@ CONFIG_SOC_BLE_SUPPORTED=y
CONFIG_SOC_BLE_MESH_SUPPORTED=y
CONFIG_SOC_BT_CLASSIC_SUPPORTED=y
CONFIG_SOC_BLUFI_SUPPORTED=y
CONFIG_SOC_BT_H2C_ENC_KEY_CTRL_ENH_VSC_SUPPORTED=y
CONFIG_SOC_ULP_HAS_ADC=y
CONFIG_SOC_PHY_COMBO_MODULE=y
CONFIG_SOC_EMAC_RMII_CLK_OUT_INTERNAL_LOOPBACK=y
CONFIG_IDF_CMAKE=y
CONFIG_IDF_TOOLCHAIN="gcc"
CONFIG_IDF_TARGET_ARCH_XTENSA=y
@@ -319,9 +329,13 @@ CONFIG_ESP_ROM_HAS_MZ_CRC32=y
CONFIG_ESP_ROM_HAS_JPEG_DECODE=y
CONFIG_ESP_ROM_HAS_UART_BUF_SWITCH=y
CONFIG_ESP_ROM_NEEDS_SWSETUP_WORKAROUND=y
CONFIG_ESP_ROM_HAS_NEWLIB=y
CONFIG_ESP_ROM_HAS_NEWLIB_NANO_FORMAT=y
CONFIG_ESP_ROM_HAS_NEWLIB_32BIT_TIME=y
CONFIG_ESP_ROM_HAS_SW_FLOAT=y
CONFIG_ESP_ROM_USB_OTG_NUM=-1
CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM=-1
CONFIG_ESP_ROM_SUPPORT_DEEP_SLEEP_WAKEUP_STUB=y
#
# Serial flasher config
@@ -339,14 +353,14 @@ CONFIG_ESPTOOLPY_FLASHFREQ_40M=y
# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set
CONFIG_ESPTOOLPY_FLASHFREQ="40m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE="2MB"
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
CONFIG_ESPTOOLPY_BEFORE_RESET=y
# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set
@@ -360,12 +374,12 @@ CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
#
# Partition Table
#
CONFIG_PARTITION_TABLE_SINGLE_APP=y
# CONFIG_PARTITION_TABLE_SINGLE_APP is not set
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
CONFIG_PARTITION_TABLE_TWO_OTA=y
# CONFIG_PARTITION_TABLE_CUSTOM is not set
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_two_ota.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
@@ -396,6 +410,8 @@ CONFIG_COMPILER_STACK_CHECK_MODE_NONE=y
# CONFIG_COMPILER_DUMP_RTL_FILES is not set
CONFIG_COMPILER_RT_LIB_GCCLIB=y
CONFIG_COMPILER_RT_LIB_NAME="gcc"
# CONFIG_COMPILER_ORPHAN_SECTIONS_WARNING is not set
CONFIG_COMPILER_ORPHAN_SECTIONS_PLACE=y
# end of Compiler options
#
@@ -421,35 +437,16 @@ CONFIG_APPTRACE_LOCK_ENABLE=y
CONFIG_BT_ALARM_MAX_NUM=50
# end of Bluetooth
#
# Console Library
#
# CONFIG_CONSOLE_SORTED_HELP is not set
# end of Console Library
#
# Driver Configurations
#
#
# Legacy ADC Configuration
#
CONFIG_ADC_DISABLE_DAC=y
# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set
#
# Legacy ADC Calibration Configuration
#
CONFIG_ADC_CAL_EFUSE_TP_ENABLE=y
CONFIG_ADC_CAL_EFUSE_VREF_ENABLE=y
CONFIG_ADC_CAL_LUT_ENABLE=y
# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy ADC Calibration Configuration
# end of Legacy ADC Configuration
#
# SPI Configuration
#
# CONFIG_SPI_MASTER_IN_IRAM is not set
CONFIG_SPI_MASTER_ISR_IN_IRAM=y
# CONFIG_SPI_SLAVE_IN_IRAM is not set
CONFIG_SPI_SLAVE_ISR_IN_IRAM=y
# end of SPI Configuration
#
# TWAI Configuration
#
@@ -462,93 +459,62 @@ CONFIG_TWAI_ERRATA_FIX_LISTEN_ONLY_DOM=y
# end of TWAI Configuration
#
# UART Configuration
# Legacy ADC Driver Configuration
#
# CONFIG_UART_ISR_IN_IRAM is not set
# end of UART Configuration
CONFIG_ADC_DISABLE_DAC=y
# CONFIG_ADC_SUPPRESS_DEPRECATE_WARN is not set
#
# GPIO Configuration
# Legacy ADC Calibration Configuration
#
# CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL is not set
# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set
# end of GPIO Configuration
CONFIG_ADC_CAL_EFUSE_TP_ENABLE=y
CONFIG_ADC_CAL_EFUSE_VREF_ENABLE=y
CONFIG_ADC_CAL_LUT_ENABLE=y
# CONFIG_ADC_CALI_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy ADC Calibration Configuration
# end of Legacy ADC Driver Configuration
#
# Sigma Delta Modulator Configuration
# Legacy DAC Driver Configurations
#
# CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set
# CONFIG_SDM_ENABLE_DEBUG_LOG is not set
# end of Sigma Delta Modulator Configuration
#
# GPTimer Configuration
#
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y
# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set
# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set
# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set
# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set
# end of GPTimer Configuration
#
# PCNT Configuration
#
# CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_PCNT_ISR_IRAM_SAFE is not set
# CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set
# CONFIG_PCNT_ENABLE_DEBUG_LOG is not set
# end of PCNT Configuration
#
# RMT Configuration
#
# CONFIG_RMT_ISR_IRAM_SAFE is not set
# CONFIG_RMT_RECV_FUNC_IN_IRAM is not set
# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set
# CONFIG_RMT_ENABLE_DEBUG_LOG is not set
# end of RMT Configuration
#
# MCPWM Configuration
#
# CONFIG_MCPWM_ISR_IRAM_SAFE is not set
# CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set
# CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set
# end of MCPWM Configuration
#
# I2S Configuration
#
# CONFIG_I2S_ISR_IRAM_SAFE is not set
# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set
# CONFIG_I2S_ENABLE_DEBUG_LOG is not set
# end of I2S Configuration
#
# DAC Configuration
#
# CONFIG_DAC_CTRL_FUNC_IN_IRAM is not set
# CONFIG_DAC_ISR_IRAM_SAFE is not set
# CONFIG_DAC_SUPPRESS_DEPRECATE_WARN is not set
# CONFIG_DAC_ENABLE_DEBUG_LOG is not set
CONFIG_DAC_DMA_AUTO_16BIT_ALIGN=y
# end of DAC Configuration
# end of Legacy DAC Driver Configurations
#
# LEDC Configuration
# Legacy MCPWM Driver Configurations
#
# CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set
# end of LEDC Configuration
# CONFIG_MCPWM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy MCPWM Driver Configurations
#
# I2C Configuration
# Legacy Timer Group Driver Configurations
#
# CONFIG_I2C_ISR_IRAM_SAFE is not set
# CONFIG_I2C_ENABLE_DEBUG_LOG is not set
# end of I2C Configuration
# CONFIG_GPTIMER_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy Timer Group Driver Configurations
#
# Legacy RMT Driver Configurations
#
# CONFIG_RMT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy RMT Driver Configurations
#
# Legacy I2S Driver Configurations
#
# CONFIG_I2S_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy I2S Driver Configurations
#
# Legacy PCNT Driver Configurations
#
# CONFIG_PCNT_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy PCNT Driver Configurations
#
# Legacy SDM Driver Configurations
#
# CONFIG_SDM_SUPPRESS_DEPRECATE_WARN is not set
# end of Legacy SDM Driver Configurations
# end of Driver Configurations
#
@@ -568,7 +534,9 @@ CONFIG_EFUSE_MAX_BLK_LEN=192
CONFIG_ESP_TLS_USING_MBEDTLS=y
# CONFIG_ESP_TLS_USE_SECURE_ELEMENT is not set
# CONFIG_ESP_TLS_CLIENT_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER is not set
# CONFIG_ESP_TLS_SERVER_SESSION_TICKETS is not set
# CONFIG_ESP_TLS_SERVER_CERT_SELECT_HOOK is not set
# CONFIG_ESP_TLS_SERVER_MIN_AUTH_MODE_OPTIONAL is not set
# CONFIG_ESP_TLS_PSK_VERIFICATION is not set
# CONFIG_ESP_TLS_INSECURE is not set
# end of ESP-TLS
@@ -588,11 +556,13 @@ CONFIG_ADC_CALI_LUT_ENABLE=y
# end of ADC Calibration Configurations
CONFIG_ADC_DISABLE_DAC_OUTPUT=y
# CONFIG_ADC_ENABLE_DEBUG_LOG is not set
# end of ADC and ADC Calibration
#
# Wireless Coexistence
#
CONFIG_ESP_COEX_ENABLED=y
# end of Wireless Coexistence
#
@@ -601,6 +571,105 @@ CONFIG_ADC_DISABLE_DAC_OUTPUT=y
CONFIG_ESP_ERR_TO_NAME_LOOKUP=y
# end of Common ESP-related
#
# ESP-Driver:DAC Configurations
#
# CONFIG_DAC_CTRL_FUNC_IN_IRAM is not set
# CONFIG_DAC_ISR_IRAM_SAFE is not set
# CONFIG_DAC_ENABLE_DEBUG_LOG is not set
CONFIG_DAC_DMA_AUTO_16BIT_ALIGN=y
# end of ESP-Driver:DAC Configurations
#
# ESP-Driver:GPIO Configurations
#
# CONFIG_GPIO_ESP32_SUPPORT_SWITCH_SLP_PULL is not set
# CONFIG_GPIO_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:GPIO Configurations
#
# ESP-Driver:GPTimer Configurations
#
CONFIG_GPTIMER_ISR_HANDLER_IN_IRAM=y
# CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM is not set
# CONFIG_GPTIMER_ISR_IRAM_SAFE is not set
# CONFIG_GPTIMER_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:GPTimer Configurations
#
# ESP-Driver:I2C Configurations
#
# CONFIG_I2C_ISR_IRAM_SAFE is not set
# CONFIG_I2C_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:I2C Configurations
#
# ESP-Driver:I2S Configurations
#
# CONFIG_I2S_ISR_IRAM_SAFE is not set
# CONFIG_I2S_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:I2S Configurations
#
# ESP-Driver:LEDC Configurations
#
# CONFIG_LEDC_CTRL_FUNC_IN_IRAM is not set
# end of ESP-Driver:LEDC Configurations
#
# ESP-Driver:MCPWM Configurations
#
# CONFIG_MCPWM_ISR_IRAM_SAFE is not set
# CONFIG_MCPWM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_MCPWM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:MCPWM Configurations
#
# ESP-Driver:PCNT Configurations
#
# CONFIG_PCNT_CTRL_FUNC_IN_IRAM is not set
# CONFIG_PCNT_ISR_IRAM_SAFE is not set
# CONFIG_PCNT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:PCNT Configurations
#
# ESP-Driver:RMT Configurations
#
# CONFIG_RMT_ISR_IRAM_SAFE is not set
# CONFIG_RMT_RECV_FUNC_IN_IRAM is not set
# CONFIG_RMT_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:RMT Configurations
#
# ESP-Driver:Sigma Delta Modulator Configurations
#
# CONFIG_SDM_CTRL_FUNC_IN_IRAM is not set
# CONFIG_SDM_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Sigma Delta Modulator Configurations
#
# ESP-Driver:SPI Configurations
#
# CONFIG_SPI_MASTER_IN_IRAM is not set
CONFIG_SPI_MASTER_ISR_IN_IRAM=y
# CONFIG_SPI_SLAVE_IN_IRAM is not set
CONFIG_SPI_SLAVE_ISR_IN_IRAM=y
# end of ESP-Driver:SPI Configurations
#
# ESP-Driver:Touch Sensor Configurations
#
# CONFIG_TOUCH_CTRL_FUNC_IN_IRAM is not set
# CONFIG_TOUCH_ISR_IRAM_SAFE is not set
# CONFIG_TOUCH_ENABLE_DEBUG_LOG is not set
# end of ESP-Driver:Touch Sensor Configurations
#
# ESP-Driver:UART Configurations
#
# CONFIG_UART_ISR_IN_IRAM is not set
# end of ESP-Driver:UART Configurations
#
# Ethernet
#
@@ -645,6 +714,7 @@ CONFIG_ESP_GDBSTUB_MAX_TASKS=32
CONFIG_ESP_HTTP_CLIENT_ENABLE_HTTPS=y
# CONFIG_ESP_HTTP_CLIENT_ENABLE_BASIC_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_DIGEST_AUTH is not set
# CONFIG_ESP_HTTP_CLIENT_ENABLE_CUSTOM_TRANSPORT is not set
# end of ESP HTTP client
#
@@ -704,6 +774,7 @@ CONFIG_ESP_MAC_ADDR_UNIVERSE_WIFI_AP=y
CONFIG_ESP_MAC_ADDR_UNIVERSE_BT=y
CONFIG_ESP_MAC_ADDR_UNIVERSE_ETH=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES_FOUR=y
CONFIG_ESP_MAC_UNIVERSAL_MAC_ADDRESSES=4
# CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_TWO is not set
CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES_FOUR=y
CONFIG_ESP32_UNIVERSAL_MAC_ADDRESSES=4
@@ -749,6 +820,8 @@ CONFIG_XTAL_FREQ_40=y
# CONFIG_XTAL_FREQ_AUTO is not set
CONFIG_XTAL_FREQ=40
# end of Main XTAL Config
CONFIG_ESP_SPI_BUS_LOCK_ISR_FUNCS_IN_IRAM=y
# end of Hardware Settings
#
@@ -787,6 +860,7 @@ CONFIG_ESP_NETIF_USES_TCPIP_WITH_BSD_API=y
#
# PHY
#
CONFIG_ESP_PHY_ENABLED=y
CONFIG_ESP_PHY_CALIBRATION_AND_DATA_STORAGE=y
# CONFIG_ESP_PHY_INIT_DATA_IN_PARTITION is not set
CONFIG_ESP_PHY_MAX_WIFI_TX_POWER=20
@@ -868,6 +942,7 @@ CONFIG_ESP_CONSOLE_UART_DEFAULT=y
# CONFIG_ESP_CONSOLE_NONE is not set
CONFIG_ESP_CONSOLE_UART=y
CONFIG_ESP_CONSOLE_UART_NUM=0
CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=0
CONFIG_ESP_CONSOLE_UART_BAUDRATE=115200
CONFIG_ESP_INT_WDT=y
CONFIG_ESP_INT_WDT_TIMEOUT_MS=300
@@ -912,7 +987,7 @@ CONFIG_ESP_IPC_ISR_ENABLE=y
# end of IPC (Inter-Processor Call)
#
# High resolution timer (esp_timer)
# ESP Timer (High Resolution Timer)
#
# CONFIG_ESP_TIMER_PROFILING is not set
CONFIG_ESP_TIME_FUNCS_USE_RTC_TIMER=y
@@ -922,11 +997,10 @@ CONFIG_ESP_TIMER_INTERRUPT_LEVEL=1
# CONFIG_ESP_TIMER_SHOW_EXPERIMENTAL is not set
CONFIG_ESP_TIMER_TASK_AFFINITY=0x0
CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0=y
CONFIG_ESP_TIMER_ISR_AFFINITY=0x1
CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0=y
# CONFIG_ESP_TIMER_SUPPORTS_ISR_DISPATCH_METHOD is not set
CONFIG_ESP_TIMER_IMPL_TG0_LAC=y
# end of High resolution timer (esp_timer)
# end of ESP Timer (High Resolution Timer)
#
# Wi-Fi
@@ -960,6 +1034,9 @@ CONFIG_ESP_WIFI_ENABLE_SAE_PK=y
CONFIG_ESP_WIFI_SOFTAP_SAE_SUPPORT=y
CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA=y
# CONFIG_ESP_WIFI_SLP_IRAM_OPT is not set
CONFIG_ESP_WIFI_SLP_DEFAULT_MIN_ACTIVE_TIME=50
CONFIG_ESP_WIFI_SLP_DEFAULT_MAX_ACTIVE_TIME=10
CONFIG_ESP_WIFI_SLP_DEFAULT_WAIT_BROADCAST_DATA_TIME=15
CONFIG_ESP_WIFI_STA_DISCONNECTED_PM_ENABLE=y
# CONFIG_ESP_WIFI_GMAC_SUPPORT is not set
CONFIG_ESP_WIFI_SOFTAP_SUPPORT=y
@@ -1034,6 +1111,8 @@ CONFIG_FATFS_PER_FILE_CACHE=y
# CONFIG_FATFS_USE_FASTSEEK is not set
CONFIG_FATFS_VFS_FSTAT_BLKSIZE=0
# CONFIG_FATFS_IMMEDIATE_FSYNC is not set
# CONFIG_FATFS_USE_LABEL is not set
CONFIG_FATFS_LINK_LOCK=y
# end of FAT Filesystem support
#
@@ -1056,12 +1135,17 @@ CONFIG_FREERTOS_IDLE_TASK_STACKSIZE=1536
CONFIG_FREERTOS_MAX_TASK_NAME_LEN=16
# CONFIG_FREERTOS_ENABLE_BACKWARD_COMPATIBILITY is not set
CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME="Tmr Svc"
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU0 is not set
# CONFIG_FREERTOS_TIMER_TASK_AFFINITY_CPU1 is not set
CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY=y
CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY=0x7FFFFFFF
CONFIG_FREERTOS_TIMER_TASK_PRIORITY=1
CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH=2048
CONFIG_FREERTOS_TIMER_QUEUE_LENGTH=10
CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE=0
CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES=1
# CONFIG_FREERTOS_USE_TRACE_FACILITY is not set
# CONFIG_FREERTOS_USE_LIST_DATA_INTEGRITY_CHECK_BYTES is not set
# CONFIG_FREERTOS_GENERATE_RUN_TIME_STATS is not set
# CONFIG_FREERTOS_USE_APPLICATION_TASK_TAG is not set
# end of Kernel
@@ -1092,6 +1176,7 @@ CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION=y
CONFIG_FREERTOS_DEBUG_OCDAWARE=y
CONFIG_FREERTOS_ENABLE_TASK_SNAPSHOT=y
CONFIG_FREERTOS_PLACE_SNAPSHOT_FUNS_INTO_FLASH=y
CONFIG_FREERTOS_NUMBER_OF_CORES=2
# end of FreeRTOS
#
@@ -1218,6 +1303,7 @@ CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT=20000
CONFIG_LWIP_TCP_SND_BUF_DEFAULT=5760
CONFIG_LWIP_TCP_WND_DEFAULT=5760
CONFIG_LWIP_TCP_RECVMBOX_SIZE=6
CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE=6
CONFIG_LWIP_TCP_QUEUE_OOSEQ=y
CONFIG_LWIP_TCP_OOSEQ_TIMEOUT=6
CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS=4
@@ -1273,6 +1359,8 @@ CONFIG_LWIP_MAX_RAW_PCBS=16
CONFIG_LWIP_SNTP_MAX_SERVERS=1
# CONFIG_LWIP_DHCP_GET_NTP_SRV is not set
CONFIG_LWIP_SNTP_UPDATE_DELAY=3600000
CONFIG_LWIP_SNTP_STARTUP_DELAY=y
CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY=5000
# end of SNTP
#
@@ -1342,6 +1430,7 @@ CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL=y
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE is not set
# CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE is not set
# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEPRECATED_LIST is not set
CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS=200
# end of Certificate Bundle
@@ -1551,6 +1640,7 @@ CONFIG_SPI_FLASH_BROWNOUT_RESET=y
#
# Features here require specific hardware (READ DOCS FIRST!)
#
CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US=50
# end of Optional and Experimental Features (READ DOCS FIRST)
# end of Main Flash configuration
@@ -1645,6 +1735,11 @@ CONFIG_WS_BUFFER_SIZE=1024
# Ultra Low Power (ULP) Co-processor
#
# CONFIG_ULP_COPROC_ENABLED is not set
#
# ULP Debugging Options
#
# end of ULP Debugging Options
# end of Ultra Low Power (ULP) Co-processor
#

View File

@@ -229,7 +229,7 @@ CONFIG_IDF_TOOLCHAIN="gcc"
CONFIG_IDF_TARGET_ARCH_XTENSA=y
CONFIG_IDF_TARGET_ARCH="xtensa"
CONFIG_IDF_TARGET="esp32"
CONFIG_IDF_INIT_VERSION="5.2.2"
CONFIG_IDF_INIT_VERSION="$IDF_INIT_VERSION"
CONFIG_IDF_TARGET_ESP32=y
CONFIG_IDF_FIRMWARE_CHIP_ID=0x0000
@@ -339,14 +339,14 @@ CONFIG_ESPTOOLPY_FLASHFREQ_40M=y
# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set
CONFIG_ESPTOOLPY_FLASHFREQ="40m"
# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set
# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set
CONFIG_ESPTOOLPY_FLASHSIZE="2MB"
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"
# CONFIG_ESPTOOLPY_HEADER_FLASHSIZE_UPDATE is not set
CONFIG_ESPTOOLPY_BEFORE_RESET=y
# CONFIG_ESPTOOLPY_BEFORE_NORESET is not set
@@ -360,12 +360,12 @@ CONFIG_ESPTOOLPY_MONITOR_BAUD=115200
#
# Partition Table
#
CONFIG_PARTITION_TABLE_SINGLE_APP=y
# CONFIG_PARTITION_TABLE_SINGLE_APP is not set
# CONFIG_PARTITION_TABLE_SINGLE_APP_LARGE is not set
# CONFIG_PARTITION_TABLE_TWO_OTA is not set
CONFIG_PARTITION_TABLE_TWO_OTA=y
# CONFIG_PARTITION_TABLE_CUSTOM is not set
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_singleapp.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions_two_ota.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x8000
CONFIG_PARTITION_TABLE_MD5=y
# end of Partition Table
@@ -1127,14 +1127,13 @@ CONFIG_HEAP_TRACING_OFF=y
# CONFIG_LOG_DEFAULT_LEVEL_NONE is not set
# CONFIG_LOG_DEFAULT_LEVEL_ERROR is not set
# CONFIG_LOG_DEFAULT_LEVEL_WARN is not set
CONFIG_LOG_DEFAULT_LEVEL_INFO=y
# CONFIG_LOG_DEFAULT_LEVEL_DEBUG is not set
# CONFIG_LOG_DEFAULT_LEVEL_INFO is not set
CONFIG_LOG_DEFAULT_LEVEL_DEBUG=y
# CONFIG_LOG_DEFAULT_LEVEL_VERBOSE is not set
CONFIG_LOG_DEFAULT_LEVEL=3
CONFIG_LOG_DEFAULT_LEVEL=4
CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT=y
# CONFIG_LOG_MAXIMUM_LEVEL_DEBUG is not set
# CONFIG_LOG_MAXIMUM_LEVEL_VERBOSE is not set
CONFIG_LOG_MAXIMUM_LEVEL=3
CONFIG_LOG_MAXIMUM_LEVEL=4
# CONFIG_LOG_MASTER_LEVEL is not set
CONFIG_LOG_COLORS=y
CONFIG_LOG_TIMESTAMP_SOURCE_RTOS=y

1
esp32_device/version.txt Normal file
View File

@@ -0,0 +1 @@
1.0.0

View File

@@ -4,6 +4,7 @@ import src.constants as constants
from cryptography.x509 import load_pem_x509_certificate
from cryptography import utils
import jwt
import json
def get_secure_origin() -> str:
@@ -75,13 +76,18 @@ def device_certificate() -> str:
return res.text
def jwt_sign(data: any, dev_id: str, privkey) -> str:
"""
Generate a JWT for client request
"""
return jwt.encode(data, privkey, algorithm="RS256", headers={"kid": dev_id})
def sync_device(dev_id: str, privkey):
"""
Synchronize device with backend
"""
encoded = jwt.encode(
{"info": device_info()}, privkey, algorithm="RS256", headers={"kid": dev_id}
)
encoded = jwt_sign({"info": device_info()}, dev_id=dev_id, privkey=privkey)
res = requests.post(
f"{args.secure_origin}/devices_api/mgmt/sync",
@@ -89,6 +95,19 @@ def sync_device(dev_id: str, privkey):
verify=args.root_ca_path,
)
print(encoded)
print(res)
print(res.text)
return json.loads(res.text)
def report_log(severity: str, message: str, dev_id: str, privkey):
"""
Report log message to server
"""
encoded = jwt_sign(
{"severity": severity, "message": message}, dev_id=dev_id, privkey=privkey
)
requests.post(
f"{args.secure_origin}/devices_api/logging/record",
json={"payload": encoded},
verify=args.root_ca_path,
)

View File

@@ -3,6 +3,10 @@ import src.api as api
import src.pki as pki
import src.utils as utils
import os
import time
# TODO : turn off all relays
# TODO : intialize GPIO
print("Check storage")
if not os.path.isdir(args.storage):
@@ -88,6 +92,13 @@ if not os.path.isfile(args.dev_crt_path):
with open(args.dev_crt_path, "w") as f:
f.write(cert)
api.report_log("Info", "Starting program main loop...", args.dev_id, args.priv_key)
print("Done. ready to operate.")
api.sync_device(args.dev_id, args.priv_key)
print("Ready to operate!.")
while True:
# TODO : implement this loop more properly
res = api.sync_device(args.dev_id, args.priv_key)
print(res)
time.sleep(5)

9
renovate.json Normal file
View File

@@ -0,0 +1,9 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"packageRules": [
{
"matchUpdateTypes": ["major", "minor", "patch"],
"automerge": true
}
]
}