Compare commits
34 Commits
b72e0d956e
..
async
| Author | SHA1 | Date | |
|---|---|---|---|
| a4eb9dceba | |||
| 17a3cf1018 | |||
| 0a5891b5be | |||
| d1a5666d18 | |||
| 4a4dea12ce | |||
| 7cdc180a6c | |||
| 44d9f9bb41 | |||
| 7881799e84 | |||
| bc1a15f27c | |||
| f2c5b86909 | |||
| dfd87f2af1 | |||
| 7f93f2d0b7 | |||
| 6b6df9eaca | |||
| 4470f281fc | |||
| 28fdd10e0a | |||
| dbbfbadf7f | |||
| 5dd8761bc0 | |||
| 9643d8e592 | |||
| d1702d69a9 | |||
| b4dedb3728 | |||
| a259a685ee | |||
| c0e6009a00 | |||
| 888c44834a | |||
| c5799902c1 | |||
| b731f182be | |||
| a02ac05443 | |||
| da332aebbe | |||
| ec3499763b | |||
| 44fba534b4 | |||
| 2380e35754 | |||
| 0130c32096 | |||
| c43eaec771 | |||
| 3d342892f1 | |||
| 3e2ce391a6 |
@@ -1 +1,2 @@
|
|||||||
/target
|
/target
|
||||||
|
Cargo.lock
|
||||||
|
|||||||
+13
-1
@@ -3,13 +3,25 @@ name = "easee"
|
|||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = ["Maxime Augier <max@xolus.net>"]
|
authors = ["Maxime Augier <max@xolus.net>"]
|
||||||
|
description = "Rust bindings for the Easee cloud API for EV charging devices"
|
||||||
|
readme = "README.md"
|
||||||
|
repository = "https://github.com/maugier/easee-rs"
|
||||||
|
license = "GPL-3.0"
|
||||||
|
keywords = ["easee"]
|
||||||
|
categories = ["api-bindings"]
|
||||||
|
|
||||||
|
|
||||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
chrono = { version = "0.4.38", features = ["serde"] }
|
chrono = { version = "0.4.38", features = ["serde"] }
|
||||||
|
futures-util = { version = "0.3.30", features = ["futures-sink"] }
|
||||||
|
reqwest = { version = "0.12.7", features = ["json"] }
|
||||||
serde = { version = "1.0.204", features = ["derive"] }
|
serde = { version = "1.0.204", features = ["derive"] }
|
||||||
serde_json = "1.0.121"
|
serde_json = "1.0.121"
|
||||||
|
serde_repr = "0.1.19"
|
||||||
thiserror = "1.0.63"
|
thiserror = "1.0.63"
|
||||||
|
tokio = "1.39.3"
|
||||||
|
tokio-tungstenite = { version = "0.23.1", features = ["tokio-rustls", "rustls-tls-native-roots"] }
|
||||||
tracing = "0.1.40"
|
tracing = "0.1.40"
|
||||||
ureq = { version = "2.10.0", features = ["json"] }
|
tungstenite = { version = "0.23.0", optional = true, features = ["rustls-tls-native-roots"] }
|
||||||
|
|||||||
@@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
# Easee-rs - Bindings for the Easee.com Cloud API.
|
||||||
|
|
||||||
|
Work in progress.
|
||||||
|
|
||||||
|
## Features and Todo
|
||||||
|
|
||||||
|
- Authn/z
|
||||||
|
- [x] Authentication and token retrieval
|
||||||
|
- [x] Persistence of tokens
|
||||||
|
- Core functionality
|
||||||
|
- [x] Enumerate sites and chargers
|
||||||
|
- [x] Read energy meter
|
||||||
|
- [x] Read charger status
|
||||||
|
- [x] Control charging (start/pause/resume/stop)
|
||||||
|
- [x] Control dynamic current limits
|
||||||
|
- Event stream
|
||||||
|
- [x] Websocket connection (raw SignalR messages)
|
||||||
|
- [x] Event decoding
|
||||||
|
- Ergonomics
|
||||||
|
- [ ] Enums for protocol constants
|
||||||
|
- [ ] Proper SignalR support with Tokio
|
||||||
|
|
||||||
|
[1]: https://easee.com
|
||||||
+512
-110
@@ -1,73 +1,192 @@
|
|||||||
use std::{io, time::{Duration, Instant}};
|
use std::{
|
||||||
|
io, ops::{Add, Mul, Sub}, time::{Duration, Instant, SystemTime, UNIX_EPOCH}
|
||||||
|
};
|
||||||
|
|
||||||
use chrono::NaiveDateTime;
|
|
||||||
use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize};
|
use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize};
|
||||||
|
use serde_repr::Deserialize_repr;
|
||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use tracing::{debug, info, instrument};
|
use tracing::{debug, info, instrument};
|
||||||
|
|
||||||
#[derive(Debug)]
|
pub use reqwest::{self, StatusCode};
|
||||||
|
|
||||||
pub struct Context {
|
pub struct Context {
|
||||||
auth_header: String,
|
auth_header: String,
|
||||||
refresh_token: String,
|
refresh_token: String,
|
||||||
token_expiration: Instant,
|
token_expiration: Instant,
|
||||||
|
on_refresh: Option<Box<dyn FnMut(&mut Self) + Send>>,
|
||||||
|
client: reqwest::Client,
|
||||||
}
|
}
|
||||||
|
|
||||||
const API_BASE: &'static str = "https://api.easee.com/api/";
|
impl std::fmt::Debug for Context {
|
||||||
const REFRESH_TOKEN_DELAY: Duration = Duration::from_secs(600);
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("Context")
|
||||||
|
.field("auth_header", &"<secret>")
|
||||||
|
.field("refresh_token", &"<secret>")
|
||||||
fn parse_iso8601<'d, D: Deserializer<'d>>(de: D) -> Result<NaiveDateTime, D::Error> {
|
.field("token_expiration", &self.token_expiration)
|
||||||
use serde::de::Error;
|
.field("on_refresh", &"[closure]")
|
||||||
let s = <&str as Deserialize>::deserialize(de)?;
|
.finish()
|
||||||
Ok(NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f")
|
}
|
||||||
.map_err(D::Error::custom)?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
const API_BASE: &str = "https://api.easee.com/api/";
|
||||||
#[serde(rename_all="camelCase")]
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||||
|
pub struct NaiveDateTime(pub chrono::NaiveDateTime);
|
||||||
|
|
||||||
|
impl<'de> Deserialize<'de> for NaiveDateTime {
|
||||||
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||||
|
use serde::de::Error;
|
||||||
|
let s = <&str as Deserialize>::deserialize(d)?;
|
||||||
|
let dt = chrono::NaiveDateTime::parse_from_str(s, "%Y-%m-%dT%H:%M:%S%.f")
|
||||||
|
.map_err(D::Error::custom)?;
|
||||||
|
Ok(NaiveDateTime(dt))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||||
|
pub struct UtcDateTime(pub chrono::DateTime<chrono::Utc>);
|
||||||
|
|
||||||
|
impl<'de> Deserialize<'de> for UtcDateTime {
|
||||||
|
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||||
|
use serde::de::Error;
|
||||||
|
let s = <&str as Deserialize>::deserialize(d)?;
|
||||||
|
let dt = chrono::DateTime::parse_from_str(s, "%+")
|
||||||
|
.map_err(D::Error::custom)?
|
||||||
|
.to_utc();
|
||||||
|
Ok(UtcDateTime(dt))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Default, Serialize, Deserialize)]
|
||||||
|
pub struct Triphase {
|
||||||
|
pub phase1: f64,
|
||||||
|
pub phase2: f64,
|
||||||
|
pub phase3: f64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Add<Triphase> for Triphase {
|
||||||
|
type Output = Triphase;
|
||||||
|
|
||||||
|
fn add(self, rhs: Triphase) -> Self::Output {
|
||||||
|
Triphase {
|
||||||
|
phase1: self.phase1 + rhs.phase1,
|
||||||
|
phase2: self.phase2 + rhs.phase2,
|
||||||
|
phase3: self.phase3 + rhs.phase3,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Sub<Triphase> for Triphase {
|
||||||
|
type Output = Triphase;
|
||||||
|
|
||||||
|
fn sub(self, rhs: Triphase) -> Self::Output {
|
||||||
|
Triphase {
|
||||||
|
phase1: self.phase1 + rhs.phase1,
|
||||||
|
phase2: self.phase2 + rhs.phase2,
|
||||||
|
phase3: self.phase3 + rhs.phase3,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Mul<f64> for Triphase {
|
||||||
|
type Output = Triphase;
|
||||||
|
|
||||||
|
fn mul(self, rhs: f64) -> Self::Output {
|
||||||
|
Triphase {
|
||||||
|
phase1: self.phase1 * rhs,
|
||||||
|
phase2: self.phase2 * rhs,
|
||||||
|
phase3: self.phase3 * rhs,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<f64> for Triphase {
|
||||||
|
fn from(value: f64) -> Self {
|
||||||
|
Triphase {
|
||||||
|
phase1: value,
|
||||||
|
phase2: value,
|
||||||
|
phase3: value,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Serialize)]
|
||||||
|
pub struct SetCurrent {
|
||||||
|
pub time_to_live: Option<i32>,
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub current: Triphase,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Charger {
|
pub struct Charger {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
pub name: String,
|
pub name: String,
|
||||||
pub product_code: u32,
|
pub product_code: u32,
|
||||||
pub color: Option<i32>,
|
pub color: Option<i32>,
|
||||||
#[serde(deserialize_with="parse_iso8601")]
|
|
||||||
pub created_on: NaiveDateTime,
|
pub created_on: NaiveDateTime,
|
||||||
|
|
||||||
#[serde(deserialize_with="parse_iso8601")]
|
|
||||||
pub updated_on: NaiveDateTime,
|
pub updated_on: NaiveDateTime,
|
||||||
pub level_of_access: u32,
|
pub level_of_access: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Clone, Copy, Debug, Deserialize_repr, Eq, Ord, PartialEq, PartialOrd)]
|
||||||
#[serde(rename_all="camelCase")]
|
#[repr(u8)]
|
||||||
|
pub enum ChargerOpMode {
|
||||||
|
Unknown = 0,
|
||||||
|
Disconnected = 1,
|
||||||
|
Paused = 2,
|
||||||
|
Charging = 3,
|
||||||
|
Finished = 4,
|
||||||
|
Error = 5,
|
||||||
|
Ready = 6,
|
||||||
|
AwaitingAuthentication = 7,
|
||||||
|
Deauthenticating = 8,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Deserialize_repr, Eq, Ord, PartialEq, PartialOrd)]
|
||||||
|
#[repr(u8)]
|
||||||
|
pub enum OutputPhase {
|
||||||
|
Unknown = 0,
|
||||||
|
L1ToN = 10,
|
||||||
|
L2ToN = 12,
|
||||||
|
L3ToN = 14,
|
||||||
|
L1ToL2 = 11,
|
||||||
|
L2ToL3 = 15,
|
||||||
|
L3ToL1 = 13,
|
||||||
|
L1L2ToN = 20,
|
||||||
|
L2L3ToN = 21,
|
||||||
|
L1L3ToL2 = 22,
|
||||||
|
L1L2L3ToN = 30,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ChargerState {
|
pub struct ChargerState {
|
||||||
pub smart_charging: bool,
|
pub smart_charging: bool,
|
||||||
pub cable_locked: bool,
|
pub cable_locked: bool,
|
||||||
pub charger_op_mode: u32,
|
pub charger_op_mode: ChargerOpMode,
|
||||||
pub total_power: f64,
|
pub total_power: f64,
|
||||||
pub session_energy: f64,
|
pub session_energy: f64,
|
||||||
pub energy_per_hour: f64,
|
pub energy_per_hour: f64,
|
||||||
|
|
||||||
#[serde(rename="wiFiRSSI")]
|
#[serde(rename = "wiFiRSSI")]
|
||||||
pub wifi_rssi: Option<i32>,
|
pub wifi_rssi: Option<i32>,
|
||||||
|
|
||||||
#[serde(rename="cellRSSI")]
|
#[serde(rename = "cellRSSI")]
|
||||||
pub cell_rssi: Option<i32>,
|
pub cell_rssi: Option<i32>,
|
||||||
|
|
||||||
#[serde(rename="localRSSI")]
|
#[serde(rename = "localRSSI")]
|
||||||
pub local_rssi: Option<i32>,
|
pub local_rssi: Option<i32>,
|
||||||
pub output_phase: u32,
|
pub output_phase: OutputPhase,
|
||||||
pub dynamic_circuit_current_p1: u32,
|
pub dynamic_circuit_current_p1: u32,
|
||||||
pub dynamic_circuit_current_p2: u32,
|
pub dynamic_circuit_current_p2: u32,
|
||||||
pub dynamic_circuit_current_p3: u32,
|
pub dynamic_circuit_current_p3: u32,
|
||||||
|
|
||||||
//#[serde(deserialize_with="parse_iso8601")]
|
pub latest_pulse: UtcDateTime,
|
||||||
//pub latest_pulse: NaiveDateTime,
|
|
||||||
pub charger_firmware: u32,
|
pub charger_firmware: u32,
|
||||||
pub voltage: f64,
|
pub voltage: f64,
|
||||||
|
|
||||||
#[serde(rename="chargerRAT")]
|
#[serde(rename = "chargerRAT")]
|
||||||
pub charger_rat: u32,
|
pub charger_rat: u32,
|
||||||
pub lock_cable_permanently: bool,
|
pub lock_cable_permanently: bool,
|
||||||
pub in_current_t2: Option<f64>,
|
pub in_current_t2: Option<f64>,
|
||||||
@@ -97,7 +216,7 @@ pub struct ChargerState {
|
|||||||
pub circuit_total_phase_conductor_current_l3: f64,
|
pub circuit_total_phase_conductor_current_l3: f64,
|
||||||
pub reason_for_no_current: u32,
|
pub reason_for_no_current: u32,
|
||||||
|
|
||||||
#[serde(rename="wiFiAPEnabled")]
|
#[serde(rename = "wiFiAPEnabled")]
|
||||||
pub wifi_ap_enabled: bool,
|
pub wifi_ap_enabled: bool,
|
||||||
pub lifetime_energy: f64,
|
pub lifetime_energy: f64,
|
||||||
pub offline_max_circuit_current_p1: u32,
|
pub offline_max_circuit_current_p1: u32,
|
||||||
@@ -111,15 +230,33 @@ pub struct ChargerState {
|
|||||||
pub derated_current: Option<f64>,
|
pub derated_current: Option<f64>,
|
||||||
pub derating_active: bool,
|
pub derating_active: bool,
|
||||||
pub connected_to_cloud: bool,
|
pub connected_to_cloud: bool,
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug,Deserialize)]
|
#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd)]
|
||||||
pub struct Address {
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct ChargingSession {
|
||||||
|
pub charger_id: Option<String>,
|
||||||
|
pub session_energy: f64,
|
||||||
|
//pub session_start: Option<NaiveDateTime>,
|
||||||
|
//pub session_stop: Option<NaiveDateTime>,
|
||||||
|
pub session_id: Option<i32>,
|
||||||
|
pub charge_duration_in_seconds: Option<u32>,
|
||||||
|
//pub first_energy_transfer_period_start: Option<NaiveDateTime>,
|
||||||
|
//pub last_energy_transfer_period_end: Option<NaiveDateTime>,
|
||||||
|
#[serde(rename = "pricePrKwhIncludingVat")]
|
||||||
|
pub price_per_kwh_including_vat: Option<f64>,
|
||||||
|
pub price_per_kwh_excluding_vat: Option<f64>,
|
||||||
|
pub vat_percentage: Option<f64>,
|
||||||
|
pub currency_id: Option<String>,
|
||||||
|
pub cost_including_vat: Option<f64>,
|
||||||
|
pub cost_excluding_vat: Option<f64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug,Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Address {}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct Site {
|
pub struct Site {
|
||||||
pub uuid: Option<String>,
|
pub uuid: Option<String>,
|
||||||
@@ -128,167 +265,432 @@ pub struct Site {
|
|||||||
pub name: Option<String>,
|
pub name: Option<String>,
|
||||||
pub level_of_access: u32,
|
pub level_of_access: u32,
|
||||||
//pub address: Address,
|
//pub address: Address,
|
||||||
pub installer_alias: Option<String>
|
pub installer_alias: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct SiteDetails {
|
||||||
|
#[serde(flatten)]
|
||||||
|
pub site: Site,
|
||||||
|
pub circuits: Vec<Circuit>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
pub struct Circuit {
|
||||||
|
pub id: u32,
|
||||||
|
pub uuid: String,
|
||||||
|
pub site_id: u32,
|
||||||
|
pub circuit_panel_id: i64,
|
||||||
|
pub panel_name: String,
|
||||||
|
pub rated_current: f64,
|
||||||
|
pub fuse: f64,
|
||||||
|
pub chargers: Vec<Charger>,
|
||||||
|
pub use_dynamic_master: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct LoginResponse {
|
pub struct LoginResponse {
|
||||||
pub access_token: String,
|
pub access_token: String,
|
||||||
pub expires_in: u32,
|
pub expires_in: u32,
|
||||||
pub access_claims: Vec<Option<String>>,
|
pub access_claims: Vec<Option<String>>,
|
||||||
pub token_type: Option<String>,
|
pub token_type: Option<String>,
|
||||||
pub refresh_token: String
|
pub refresh_token: String,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug,Error)]
|
#[allow(dead_code)]
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct CommandReply {
|
||||||
|
command_id: u64,
|
||||||
|
device: String,
|
||||||
|
ticks: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
pub enum ApiError {
|
pub enum ApiError {
|
||||||
|
/// HTTP call caused an IO error
|
||||||
#[error("io: {0}")]
|
#[error("io: {0}")]
|
||||||
IO(#[from] io::Error),
|
IO(#[from] io::Error),
|
||||||
|
|
||||||
|
/// HTTP call failed (404, etc)
|
||||||
#[error("ureq")]
|
#[error("ureq")]
|
||||||
Ureq(#[from] ureq::Error),
|
HTTP(#[source] Box<reqwest::Error>),
|
||||||
|
|
||||||
|
/// HTTP call succeeded but the returned JSON document didn't match the expected format
|
||||||
#[error("unexpected data: {1} when processing {0}")]
|
#[error("unexpected data: {1} when processing {0}")]
|
||||||
UnexpectedData(serde_json::Value, serde_json::Error),
|
UnexpectedData(serde_json::Value, serde_json::Error),
|
||||||
|
|
||||||
|
/// A JSON datetime field did not contain a string
|
||||||
#[error("could not deserialize time string")]
|
#[error("could not deserialize time string")]
|
||||||
DeserializeFail,
|
DeserializeFail,
|
||||||
|
|
||||||
|
/// A JSON datetime field could not be parsed
|
||||||
#[error("format error: {0}")]
|
#[error("format error: {0}")]
|
||||||
FormatError(#[from] chrono::ParseError)
|
FormatError(#[from] chrono::ParseError),
|
||||||
|
|
||||||
|
#[error("Invalid ID: {0:?}")]
|
||||||
|
InvalidID(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<reqwest::Error> for ApiError {
|
||||||
|
fn from(value: reqwest::Error) -> Self {
|
||||||
|
ApiError::HTTP(Box::new(value))
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
trait JsonExplicitError {
|
trait JsonExplicitError {
|
||||||
fn into_json_with_error<T: DeserializeOwned>(self) -> Result<T, ApiError>;
|
/// Explicitely report the received JSON object we failed to parse
|
||||||
|
async fn into_json_with_error<T: DeserializeOwned>(self) -> Result<T, ApiError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
impl JsonExplicitError for ureq::Response {
|
impl JsonExplicitError for reqwest::Response {
|
||||||
fn into_json_with_error<T: DeserializeOwned>(self) -> Result<T, ApiError> {
|
async fn into_json_with_error<T: DeserializeOwned>(self) -> Result<T, ApiError> {
|
||||||
let resp: serde_json::Value = self.into_json()?;
|
let resp: serde_json::Value = self.json().await?;
|
||||||
let parsed = T::deserialize(&resp);
|
let parsed = T::deserialize(&resp);
|
||||||
parsed.map_err(|e| ApiError::UnexpectedData(resp, e))
|
parsed.map_err(|e| ApiError::UnexpectedData(resp, e))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum TokenParseError {
|
||||||
|
#[error("Bad line count")]
|
||||||
|
IncorrectLineCount,
|
||||||
|
|
||||||
|
#[error("Parse error: {0}")]
|
||||||
|
ParseIntError(#[from] std::num::ParseIntError),
|
||||||
|
}
|
||||||
|
|
||||||
impl Context {
|
impl Context {
|
||||||
|
fn from_login_response(resp: LoginResponse, client: reqwest::Client) -> Self {
|
||||||
pub fn from_tokens(access_token: &str, refresh_token: String, expires_in: u32) -> Self {
|
Self {
|
||||||
Self { auth_header: format!("Bearer {}", access_token),
|
auth_header: format!("Bearer {}", &resp.access_token),
|
||||||
refresh_token,
|
refresh_token: resp.refresh_token,
|
||||||
token_expiration: Instant::now() + Duration::from_secs(expires_in as u64) - REFRESH_TOKEN_DELAY }
|
token_expiration: (Instant::now() + Duration::from_secs(resp.expires_in as u64)),
|
||||||
|
on_refresh: None,
|
||||||
|
client,
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn from_login_response(resp: LoginResponse) -> Self {
|
pub fn from_saved(saved: &str) -> Result<Self, TokenParseError> {
|
||||||
Self::from_tokens(&resp.access_token, resp.refresh_token, resp.expires_in)
|
let lines: Vec<&str> = saved.lines().collect();
|
||||||
|
let &[token, refresh, expire] = &*lines else {
|
||||||
|
return Err(TokenParseError::IncorrectLineCount);
|
||||||
|
};
|
||||||
|
|
||||||
|
let expire: u64 = expire.parse()?;
|
||||||
|
let token_expiration = Instant::now()
|
||||||
|
+ (UNIX_EPOCH + Duration::from_secs(expire))
|
||||||
|
.duration_since(SystemTime::now())
|
||||||
|
.unwrap_or_default();
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
auth_header: format!("Bearer {}", token),
|
||||||
|
refresh_token: refresh.to_owned(),
|
||||||
|
token_expiration,
|
||||||
|
on_refresh: None,
|
||||||
|
client: reqwest::Client::new(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn from_login(user: &str, password: &str) -> Result<Self, ApiError> {
|
pub fn on_refresh<F: FnMut(&mut Self) + Send + 'static>(mut self, on_refresh: F) -> Self {
|
||||||
|
self.on_refresh = Some(Box::new(on_refresh));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save(&self) -> String {
|
||||||
|
let expiration = (SystemTime::now() + (self.token_expiration - Instant::now()))
|
||||||
|
.duration_since(UNIX_EPOCH)
|
||||||
|
.unwrap();
|
||||||
|
format!(
|
||||||
|
"{}\n{}\n{}\n",
|
||||||
|
self.auth_token(),
|
||||||
|
self.refresh_token,
|
||||||
|
expiration.as_secs()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve access tokens online, by logging in with the provided credentials
|
||||||
|
pub async fn from_login(user: &str, password: &str) -> Result<Self, ApiError> {
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
#[serde(rename_all="camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct Params<'t> { user_name: &'t str, password: &'t str }
|
struct Params<'t> {
|
||||||
|
user_name: &'t str,
|
||||||
|
password: &'t str,
|
||||||
|
}
|
||||||
|
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
|
||||||
info!("Logging into API");
|
info!("Logging into API");
|
||||||
let url: String = format!("{}accounts/login", API_BASE);
|
let url: String = format!("{}accounts/login", API_BASE);
|
||||||
let resp: LoginResponse = ureq::post(&url)
|
let resp: LoginResponse = client.post(&url)
|
||||||
.send_json(Params { user_name: user, password } )?
|
.json(&Params {
|
||||||
.into_json_with_error()?;
|
user_name: user,
|
||||||
|
password,
|
||||||
|
})
|
||||||
|
.send().await?
|
||||||
|
.into_json_with_error().await?;
|
||||||
|
|
||||||
Ok(Self::from_login_response(resp))
|
Ok(Self::from_login_response(resp, client))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn check_expired(&mut self) -> Result<(), ApiError> {
|
/// Check if the token has reached its expiration date
|
||||||
|
async fn check_expired(&mut self) -> Result<(), ApiError> {
|
||||||
if self.token_expiration < Instant::now() {
|
if self.token_expiration < Instant::now() {
|
||||||
debug!("Token has expired");
|
debug!("Token has expired");
|
||||||
self.refresh_token()?;
|
self.refresh_token().await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn refresh_token(&mut self) -> Result<(), ApiError> {
|
pub(crate) fn auth_token(&self) -> &str {
|
||||||
|
&self.auth_header[7..]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Use the refresh token to refresh credentials
|
||||||
|
pub async fn refresh_token(&mut self) -> Result<(), ApiError> {
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
#[serde(rename_all="camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
struct Params<'t> { refresh_token: &'t str }
|
struct Params<'t> {
|
||||||
|
refresh_token: &'t str,
|
||||||
|
}
|
||||||
|
|
||||||
info!("Refreshing access token");
|
info!("Refreshing access token");
|
||||||
let params = Params { refresh_token: &self.refresh_token };
|
let params = Params {
|
||||||
|
refresh_token: &self.refresh_token,
|
||||||
|
};
|
||||||
let url = format!("{}accounts/refresh_token", API_BASE);
|
let url = format!("{}accounts/refresh_token", API_BASE);
|
||||||
let resp: LoginResponse = ureq::post(&url)
|
let resp: LoginResponse = self.client.post(&url)
|
||||||
.set("Content-type", "application/json")
|
.header("Content-type", "application/json")
|
||||||
.send_json(¶ms)?
|
.json(¶ms)
|
||||||
.into_json_with_error()?;
|
.send().await?
|
||||||
|
.into_json_with_error().await?;
|
||||||
|
|
||||||
*self = Self::from_login_response(resp);
|
*self = Self::from_login_response(resp, self.client.clone());
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn sites(&mut self) -> Result<Vec<Site>, ApiError> {
|
/// List all sites available to the user
|
||||||
self.get("sites")
|
pub async fn sites(&mut self) -> Result<Vec<Site>, ApiError> {
|
||||||
|
self.get("sites").await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn chargers(&mut self) -> Result<Vec<Charger>, ApiError> {
|
pub async fn site(&mut self, id: i32) -> Result<SiteDetails, ApiError> {
|
||||||
self.get("chargers")
|
self.get(&format!("sites/{id}")).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// List all chargers available to the user
|
||||||
|
pub async fn chargers(&mut self) -> Result<Vec<Charger>, ApiError> {
|
||||||
|
self.get("chargers").await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn charger(&mut self, id: &str) -> Result<Charger, ApiError> {
|
||||||
|
if !id.chars().all(char::is_alphanumeric) {
|
||||||
|
return Err(ApiError::InvalidID(id.to_owned()));
|
||||||
|
}
|
||||||
|
self.get(&format!("chargers/{}", id)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn circuit(&mut self, site_id: u32, circuit_id: u32) -> Result<Circuit, ApiError> {
|
||||||
|
self.get(&format!("site/{site_id}/circuit/{circuit_id}")).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn circuit_dynamic_current(
|
||||||
|
&mut self,
|
||||||
|
site_id: u32,
|
||||||
|
circuit_id: u32,
|
||||||
|
) -> Result<Triphase, ApiError> {
|
||||||
|
self.get(&format!(
|
||||||
|
"sites/{site_id}/circuits/{circuit_id}/dynamicCurrent"
|
||||||
|
)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_circuit_dynamic_current(
|
||||||
|
&mut self,
|
||||||
|
site_id: u32,
|
||||||
|
circuit_id: u32,
|
||||||
|
current: SetCurrent,
|
||||||
|
) -> Result<(), ApiError> {
|
||||||
|
self.post(
|
||||||
|
&format!("sites/{site_id}/circuits/{circuit_id}/dynamicCurrent"),
|
||||||
|
¤t,
|
||||||
|
).await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[instrument]
|
#[instrument]
|
||||||
fn get<T: DeserializeOwned>(&mut self, path: &str) -> Result<T, ApiError> {
|
async fn get<T: DeserializeOwned>(&mut self, path: &str) -> Result<T, ApiError> {
|
||||||
self.check_expired()?;
|
self.check_expired().await?;
|
||||||
let url: String = format!("{}{}", API_BASE, path);
|
let url: String = format!("{}{}", API_BASE, path);
|
||||||
let req = ureq::get(&url)
|
|
||||||
.set("Accept", "application/json")
|
|
||||||
.set("Authorization", &self.auth_header);
|
|
||||||
|
|
||||||
let mut resp = req.clone().call()?;
|
let req = self.client.get(url)
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("Authorization", &self.auth_header)
|
||||||
|
.build()?;
|
||||||
|
|
||||||
|
let mut resp = self.client.execute(req.try_clone().unwrap()).await?;
|
||||||
|
|
||||||
if resp.status() == 401 {
|
if resp.status() == 401 {
|
||||||
self.refresh_token()?;
|
self.refresh_token().await?;
|
||||||
resp = req.call()?
|
resp = self.client.execute(req).await?
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(resp.into_json_with_error()?)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn post<T: DeserializeOwned, P: Serialize>(&mut self, path: &str, params: &P) -> Result<T, ApiError> {
|
resp.into_json_with_error().await
|
||||||
self.check_expired()?;
|
|
||||||
let url: String = format!("{}{}", API_BASE, path);
|
|
||||||
let req = ureq::post(&url)
|
|
||||||
.set("Accept", "application/json")
|
|
||||||
.set("Authorization", &self.auth_header);
|
|
||||||
|
|
||||||
let mut resp = req.clone().send_json(params)?;
|
|
||||||
|
|
||||||
if resp.status() == 401 {
|
|
||||||
self.refresh_token()?;
|
|
||||||
resp = req.send_json(params)?
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(resp.into_json_with_error()?)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn maybe_get<T: DeserializeOwned>(&mut self, path: &str) -> Result<Option<T>, ApiError> {
|
||||||
|
match self.get(path).await {
|
||||||
|
Ok(r) => Ok(Some(r)),
|
||||||
|
Err(ApiError::HTTP(e)) if e.status() == Some(StatusCode::NOT_FOUND)=> Ok(None),
|
||||||
|
Err(other) => Err(other),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn post<T: DeserializeOwned, P: Serialize>(
|
||||||
|
&mut self,
|
||||||
|
path: &str,
|
||||||
|
params: &P,
|
||||||
|
) -> Result<T, ApiError> {
|
||||||
|
let url: String = format!("{}{}", API_BASE, path);
|
||||||
|
self.post_raw(&url, params).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) async fn post_raw<T: DeserializeOwned, P: Serialize>(
|
||||||
|
&mut self,
|
||||||
|
url: &str,
|
||||||
|
params: &P,
|
||||||
|
) -> Result<T, ApiError> {
|
||||||
|
self.check_expired().await?;
|
||||||
|
let req = self.client.post(url)
|
||||||
|
.header("Accept", "application/json")
|
||||||
|
.header("Authorization", &self.auth_header)
|
||||||
|
.json(params);
|
||||||
|
|
||||||
|
let mut resp = req
|
||||||
|
.try_clone().unwrap()
|
||||||
|
.send().await?;
|
||||||
|
|
||||||
|
if resp.status() == 401 {
|
||||||
|
self.refresh_token().await?;
|
||||||
|
resp = req.send().await?
|
||||||
|
}
|
||||||
|
|
||||||
|
resp.into_json_with_error().await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Energy meter reading
|
||||||
#[derive(Debug, Deserialize)]
|
#[derive(Debug, Deserialize)]
|
||||||
#[serde(rename_all="camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct MeterReading {
|
pub struct MeterReading {
|
||||||
|
/// ID of the charger
|
||||||
pub charger_id: String,
|
pub charger_id: String,
|
||||||
|
|
||||||
|
/// Lifetime consumed energy, in kWh
|
||||||
pub life_time_energy: f64,
|
pub life_time_energy: f64,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Site {
|
impl Site {
|
||||||
pub fn lifetime_energy(&self, ctx: &mut Context) -> Result<Vec<MeterReading>, ApiError> {
|
/// Read all energy meters from the given site
|
||||||
ctx.get(&format!("sites/{}/energy", self.id))
|
pub async fn lifetime_energy(&self, ctx: &mut Context) -> Result<Vec<MeterReading>, ApiError> {
|
||||||
|
ctx.get(&format!("sites/{}/energy", self.id)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn details(&self, ctx: &mut Context) -> Result<SiteDetails, ApiError> {
|
||||||
|
ctx.get(&format!("sites/{}", self.id)).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Circuit {
|
||||||
|
fn dynamic_current_path(&self) -> String {
|
||||||
|
format!("sites/{}/circuits/{}/dynamicCurrent", self.site_id, self.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn dynamic_current(&self, ctx: &mut Context) -> Result<Triphase, ApiError> {
|
||||||
|
ctx.circuit_dynamic_current(self.site_id, self.id).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn set_dynamic_current(
|
||||||
|
&self,
|
||||||
|
ctx: &mut Context,
|
||||||
|
current: SetCurrent,
|
||||||
|
) -> Result<(), ApiError> {
|
||||||
|
ctx.post(&self.dynamic_current_path(), ¤t).await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Charger {
|
impl Charger {
|
||||||
pub fn enable_smart_charging(&self, ctx: &mut Context) -> Result<(), ApiError> {
|
/// Enable "smart charging" on the charger. This just turns the LED blue, and disables basic charging plans.
|
||||||
|
pub async fn enable_smart_charging(&self, ctx: &mut Context) -> Result<(), ApiError> {
|
||||||
let url = format!("chargers/{}/commands/smart_charging", &self.id);
|
let url = format!("chargers/{}/commands/smart_charging", &self.id);
|
||||||
ctx.post(&url, &())
|
ctx.post(&url, &()).await
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn state(&self, ctx: &mut Context) -> Result<ChargerState, ApiError> {
|
/// Read the state of a charger
|
||||||
|
pub async fn state(&self, ctx: &mut Context) -> Result<ChargerState, ApiError> {
|
||||||
let url = format!("chargers/{}/state", self.id);
|
let url = format!("chargers/{}/state", self.id);
|
||||||
ctx.get(&url)
|
ctx.get(&url).await
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
/// Read info about the ongoing charging session
|
||||||
|
pub async fn ongoing_session(&self, ctx: &mut Context) -> Result<Option<ChargingSession>, ApiError> {
|
||||||
|
ctx.maybe_get(&format!("chargers/{}/sessions/ongoing", &self.id)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read info about the last charging session (not including ongoing one)
|
||||||
|
pub async fn latest_session(&self, ctx: &mut Context) -> Result<Option<ChargingSession>, ApiError> {
|
||||||
|
ctx.maybe_get(&format!("chargers/{}/sessions/latest", &self.id)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn command(&self, ctx: &mut Context, command: &str) -> Result<CommandReply, ApiError> {
|
||||||
|
ctx.post(&format!("chargers/{}/commands/{}", self.id, command), &()).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn start(&self, ctx: &mut Context) -> Result<(), ApiError> {
|
||||||
|
self.command(ctx, "start_charging").await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn pause(&self, ctx: &mut Context) -> Result<(), ApiError> {
|
||||||
|
self.command(ctx, "pause_charging").await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn resume(&self, ctx: &mut Context) -> Result<(), ApiError> {
|
||||||
|
self.command(ctx, "resume_charging").await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn stop(&self, ctx: &mut Context) -> Result<(), ApiError> {
|
||||||
|
self.command(ctx, "stop_charging").await?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod test {
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use super::Context;
|
||||||
|
#[test]
|
||||||
|
fn token_save() {
|
||||||
|
|
||||||
|
let client = reqwest::Client::new();
|
||||||
|
|
||||||
|
let ctx = Context {
|
||||||
|
auth_header: "Bearer aaaaaaa0".to_owned(),
|
||||||
|
refresh_token: "abcdef".to_owned(),
|
||||||
|
token_expiration: Instant::now() + Duration::from_secs(1234),
|
||||||
|
on_refresh: None,
|
||||||
|
client: client.clone(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let saved = ctx.save();
|
||||||
|
let ctx2 = Context::from_saved(&saved).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(&ctx.auth_header, &ctx2.auth_header);
|
||||||
|
assert_eq!(&ctx.refresh_token, &ctx2.refresh_token);
|
||||||
|
assert!((ctx.token_expiration - ctx2.token_expiration) < Duration::from_secs(5))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1 +1,10 @@
|
|||||||
pub mod api;
|
pub mod api;
|
||||||
|
|
||||||
|
#[cfg(feature = "tungstenite")]
|
||||||
|
pub mod stream;
|
||||||
|
|
||||||
|
#[cfg(feature = "tungstenite")]
|
||||||
|
pub mod signalr;
|
||||||
|
|
||||||
|
#[cfg(feature = "tungstenite")]
|
||||||
|
pub mod observation;
|
||||||
|
|||||||
@@ -0,0 +1,375 @@
|
|||||||
|
use serde::{de::{DeserializeOwned, IntoDeserializer}, Deserialize};
|
||||||
|
use serde_json::json;
|
||||||
|
use serde_repr::Deserialize_repr;
|
||||||
|
use std::num::{ParseFloatError, ParseIntError};
|
||||||
|
use thiserror::Error;
|
||||||
|
use tracing::info;
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
api::{ChargerOpMode, Context, OutputPhase, UtcDateTime},
|
||||||
|
signalr::{self, StreamError},
|
||||||
|
stream::NegotiateError,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Deserialize_repr)]
|
||||||
|
#[repr(u8)]
|
||||||
|
pub enum PilotMode {
|
||||||
|
Disconnected = b'A',
|
||||||
|
Connected = b'B',
|
||||||
|
Charging = b'C',
|
||||||
|
NeedsVentilation = b'D',
|
||||||
|
FaultDetected = b'F',
|
||||||
|
Unknown = b'\x00',
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<&str> for PilotMode {
|
||||||
|
fn from(value: &str) -> Self {
|
||||||
|
use PilotMode::*;
|
||||||
|
match value {
|
||||||
|
"A" => Disconnected,
|
||||||
|
"B" => Connected,
|
||||||
|
"C" => Charging,
|
||||||
|
"D" => NeedsVentilation,
|
||||||
|
"F" => FaultDetected,
|
||||||
|
_ => Unknown,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Deserialize_repr)]
|
||||||
|
#[repr(u8)]
|
||||||
|
pub enum PhaseMode {
|
||||||
|
Ignore = 0,
|
||||||
|
Phase1 = 1,
|
||||||
|
Auto = 2,
|
||||||
|
Phase2 = 3,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug)]
|
||||||
|
pub enum InputPin {
|
||||||
|
T1,
|
||||||
|
T2,
|
||||||
|
T3,
|
||||||
|
T4,
|
||||||
|
T5,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, Deserialize_repr)]
|
||||||
|
#[repr(u8)]
|
||||||
|
enum DataType {
|
||||||
|
Boolean = 2,
|
||||||
|
Double = 3,
|
||||||
|
Integer = 4,
|
||||||
|
String = 6,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub enum ObservationData {
|
||||||
|
Boolean(bool),
|
||||||
|
Double(f64),
|
||||||
|
Integer(i64),
|
||||||
|
String(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Error, Debug)]
|
||||||
|
pub enum ParseError {
|
||||||
|
#[error("integer `{0}`: {1}")]
|
||||||
|
Integer(String, ParseIntError),
|
||||||
|
|
||||||
|
#[error("double `{0}: {1}")]
|
||||||
|
Double(String, ParseFloatError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ObservationData {
|
||||||
|
fn from_dynamic(value: String, data_type: DataType) -> Result<ObservationData, ParseError> {
|
||||||
|
Ok(match data_type {
|
||||||
|
DataType::Boolean => ObservationData::Boolean(
|
||||||
|
match &*value {
|
||||||
|
"False"|"false" => { false },
|
||||||
|
"True"|"true" => { true }
|
||||||
|
other => other
|
||||||
|
.parse::<i64>()
|
||||||
|
.map_err(move |e| ParseError::Integer(value, e))?
|
||||||
|
!= 0,
|
||||||
|
}
|
||||||
|
),
|
||||||
|
DataType::Double => ObservationData::Double(
|
||||||
|
value
|
||||||
|
.parse()
|
||||||
|
.map_err(move |e| ParseError::Double(value, e))?,
|
||||||
|
),
|
||||||
|
DataType::Integer => ObservationData::Integer(
|
||||||
|
value
|
||||||
|
.parse()
|
||||||
|
.map_err(move |e| ParseError::Integer(value, e))?,
|
||||||
|
),
|
||||||
|
DataType::String => ObservationData::String(value),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/*
|
||||||
|
fn dynamic_type(&self) -> DataType {
|
||||||
|
match self {
|
||||||
|
ObservationData::Boolean(_) => DataType::Boolean,
|
||||||
|
ObservationData::Double(_) => DataType::Double,
|
||||||
|
ObservationData::Integer(_) => DataType::Integer,
|
||||||
|
ObservationData::String(_) => DataType::String,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||||
|
pub struct ReasonForNoCurrent(u16);
|
||||||
|
|
||||||
|
impl std::fmt::Display for ReasonForNoCurrent {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
write!(
|
||||||
|
f,
|
||||||
|
"{}",
|
||||||
|
match self.0 {
|
||||||
|
0 => "OK",
|
||||||
|
1 => "LoadBalance: circuit too low",
|
||||||
|
2 => "LoadBalance: dynamic circuit too low",
|
||||||
|
3 => "LoadBalance: max dynamic offline",
|
||||||
|
4 => "LoadBalance: circuit fuse too low",
|
||||||
|
5 => "LoadBalance: waiting in queue",
|
||||||
|
6 => "LoadBalance: waiting in charged queue",
|
||||||
|
7 => "Error: illegal grid type",
|
||||||
|
8 => "Error: not received request from car",
|
||||||
|
9 => "Error: master communication lost",
|
||||||
|
10 => "Error: no current from equalizer",
|
||||||
|
11 => "Error: no current, phase disconnected",
|
||||||
|
25 => "Error: limited by circuit fuse",
|
||||||
|
26 => "Error: limited by circuit max current",
|
||||||
|
27 => "Error: limited by dynamic circuit current",
|
||||||
|
28 => "Error: limited by equalizer",
|
||||||
|
29 => "Error: limited by circuit load balancing",
|
||||||
|
30 => "Error: limited by offline settings",
|
||||||
|
53 => "Info: charger disabled",
|
||||||
|
54 => "Waiting: pending schedule",
|
||||||
|
55 => "Waiting: pending authorization",
|
||||||
|
56 => "Error: charger in error state",
|
||||||
|
57 => "Error: Erratic EV",
|
||||||
|
75 => "Cable: limited by cable rating",
|
||||||
|
76 => "Schedule: limited by schedule",
|
||||||
|
77 => "Charger limit: limited by charger max current",
|
||||||
|
78 => "Charger Limit: limited by dynamic charger current",
|
||||||
|
79 => "Car limit: limited by car not charging",
|
||||||
|
80 => "Local: limited by local adjustment",
|
||||||
|
81 => "Car limit: limited by car",
|
||||||
|
100 => "Error: undefined",
|
||||||
|
other => return write!(f, "Code {other}"),
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Observation {
|
||||||
|
SelfTestResult(String),
|
||||||
|
SelfTestDetails(String),
|
||||||
|
WifiEvent(i64),
|
||||||
|
ChargerOfflineReason(i64),
|
||||||
|
CircuitMaxCurrent { phase: u8, amperes: f64 },
|
||||||
|
SiteID(String),
|
||||||
|
IsEnabled(bool),
|
||||||
|
Temperature(i64),
|
||||||
|
TriplePhase(bool),
|
||||||
|
DynamicChargerCurrent(f64),
|
||||||
|
CircuitTotalCurrent { phase: u8, amperes: f64 },
|
||||||
|
|
||||||
|
ICCID(String),
|
||||||
|
MobileNetworkOperator(String),
|
||||||
|
|
||||||
|
ReasonForNoCurrent(ReasonForNoCurrent),
|
||||||
|
|
||||||
|
LocalPreauthEnabled(bool),
|
||||||
|
LocalOfflineAuthEnabled(bool),
|
||||||
|
AllowOfflineTxUnknownId(bool),
|
||||||
|
|
||||||
|
PilotMode(PilotMode),
|
||||||
|
SmartCharging(bool),
|
||||||
|
CableLocked(bool),
|
||||||
|
CableRating(f64),
|
||||||
|
|
||||||
|
LedMode(i64),
|
||||||
|
|
||||||
|
UserId(String),
|
||||||
|
ChargerOpMode(ChargerOpMode),
|
||||||
|
IntCurrent { pin: InputPin, current: f64 },
|
||||||
|
IntVoltage { pins: (InputPin, InputPin), voltage: f64 },
|
||||||
|
|
||||||
|
ActiveOutputPhase(OutputPhase),
|
||||||
|
MaximumTemperature(i64),
|
||||||
|
|
||||||
|
TotalPower(f64),
|
||||||
|
EnergyPerHour(f64),
|
||||||
|
LifetimeEnergy(f64),
|
||||||
|
LifetimeRelaySwitches(i64),
|
||||||
|
LifetimeHours(i64),
|
||||||
|
|
||||||
|
Unknown { code: u16, value: ObservationData },
|
||||||
|
}
|
||||||
|
|
||||||
|
fn op_mode_from_int(mode: i64) -> ChargerOpMode {
|
||||||
|
use ChargerOpMode::*;
|
||||||
|
match mode {
|
||||||
|
1 => Disconnected,
|
||||||
|
2 => Paused,
|
||||||
|
3 => Charging,
|
||||||
|
4 => Finished,
|
||||||
|
5 => Error,
|
||||||
|
6 => Ready,
|
||||||
|
_ => Unknown,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deserialize_i64<T: DeserializeOwned>(value: i64) -> Option<T> {
|
||||||
|
T::deserialize(<i64 as IntoDeserializer<serde::de::value::Error>>::into_deserializer(value)).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Observation {
|
||||||
|
fn try_from_data(code: u16, data: ObservationData) -> Observation {
|
||||||
|
use InputPin::*;
|
||||||
|
use Observation::*;
|
||||||
|
use ObservationData::*;
|
||||||
|
match (code, data) {
|
||||||
|
(1, String(result)) => SelfTestResult(result),
|
||||||
|
(2, String(details)) => SelfTestDetails(details),
|
||||||
|
(10, Integer(wifi)) => WifiEvent(wifi),
|
||||||
|
(11, Integer(reason)) => ChargerOfflineReason(reason),
|
||||||
|
(22, Double(amperes)) => CircuitMaxCurrent { phase: 1, amperes },
|
||||||
|
(23, Double(amperes)) => CircuitMaxCurrent { phase: 2, amperes },
|
||||||
|
(24, Double(amperes)) => CircuitMaxCurrent { phase: 3, amperes },
|
||||||
|
(26, String(site)) => SiteID(site),
|
||||||
|
(31, Boolean(enabled)) => IsEnabled(enabled),
|
||||||
|
(32, Integer(temperature)) => Temperature(temperature),
|
||||||
|
(38, Integer(1)) => TriplePhase(false),
|
||||||
|
(38, Integer(3)) => TriplePhase(true),
|
||||||
|
(46, Integer(mode)) => LedMode(mode),
|
||||||
|
(48, Double(current)) => DynamicChargerCurrent(current),
|
||||||
|
(73, Double(amperes)) => CircuitTotalCurrent { phase: 1, amperes },
|
||||||
|
(74, Double(amperes)) => CircuitTotalCurrent { phase: 2, amperes },
|
||||||
|
(75, Double(amperes)) => CircuitTotalCurrent { phase: 3, amperes },
|
||||||
|
(81, String(iccid)) => ICCID(iccid),
|
||||||
|
(84, String(operator)) => MobileNetworkOperator(operator),
|
||||||
|
(96, Integer(reason)) => ReasonForNoCurrent(self::ReasonForNoCurrent(reason as u16)),
|
||||||
|
(100, String(l)) => PilotMode(super::observation::PilotMode::from(&*l)),
|
||||||
|
(102, Boolean(enabled)) => SmartCharging(enabled),
|
||||||
|
(103, Boolean(locked)) => CableLocked(locked),
|
||||||
|
(104, Double(amps)) => CableRating(amps),
|
||||||
|
(107, String(tok_rev)) => UserId(tok_rev.chars().rev().collect()),
|
||||||
|
(109, Integer(mode)) => ChargerOpMode(op_mode_from_int(mode)),
|
||||||
|
(110, Integer(mode)) => ActiveOutputPhase(deserialize_i64(mode).unwrap_or(OutputPhase::Unknown)),
|
||||||
|
(120, Double(power)) => TotalPower(power),
|
||||||
|
(122, Double(energy)) => EnergyPerHour(energy),
|
||||||
|
(124, Double(energy)) => LifetimeEnergy(energy),
|
||||||
|
(125, Integer(count)) => LifetimeRelaySwitches(count),
|
||||||
|
(126, Integer(hours)) => LifetimeHours(hours),
|
||||||
|
(150, Integer(degrees)) => MaximumTemperature(degrees),
|
||||||
|
(182, Double(current)) => IntCurrent { pin: T2, current },
|
||||||
|
(183, Double(current)) => IntCurrent { pin: T3, current },
|
||||||
|
(184, Double(current)) => IntCurrent { pin: T4, current },
|
||||||
|
(185, Double(current)) => IntCurrent { pin: T5, current },
|
||||||
|
(190, Double(voltage)) => IntVoltage { pins: (T1, T2), voltage },
|
||||||
|
(191, Double(voltage)) => IntVoltage { pins: (T1, T3), voltage },
|
||||||
|
(192, Double(voltage)) => IntVoltage { pins: (T1, T4), voltage },
|
||||||
|
(193, Double(voltage)) => IntVoltage { pins: (T1, T5), voltage },
|
||||||
|
(194, Double(voltage)) => IntVoltage { pins: (T2, T3), voltage },
|
||||||
|
(195, Double(voltage)) => IntVoltage { pins: (T2, T4), voltage },
|
||||||
|
(196, Double(voltage)) => IntVoltage { pins: (T2, T5), voltage },
|
||||||
|
(197, Double(voltage)) => IntVoltage { pins: (T3, T4), voltage },
|
||||||
|
(198, Double(voltage)) => IntVoltage { pins: (T3, T5), voltage },
|
||||||
|
(199, Double(voltage)) => IntVoltage { pins: (T4, T5), voltage },
|
||||||
|
|
||||||
|
|
||||||
|
(code, value) => Unknown { code, value },
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Event {
|
||||||
|
pub charger: String,
|
||||||
|
pub observation: Observation,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Stream {
|
||||||
|
inner: signalr::Stream,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum ObservationError {
|
||||||
|
#[error("stream: {0}")]
|
||||||
|
Stream(#[from] StreamError),
|
||||||
|
|
||||||
|
#[error("Protocol error")]
|
||||||
|
Protocol(signalr::Message),
|
||||||
|
|
||||||
|
#[error("JSON: {0}")]
|
||||||
|
Deserialize(#[from] serde_json::Error),
|
||||||
|
|
||||||
|
#[error("Parsing: {0}")]
|
||||||
|
Parsing(#[from] ParseError),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Deserialize, Debug)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct ProductUpdate {
|
||||||
|
data_type: DataType,
|
||||||
|
id: u16,
|
||||||
|
mid: String,
|
||||||
|
timestamp: UtcDateTime,
|
||||||
|
value: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream {
|
||||||
|
pub async fn from_context(ctx: &mut Context) -> Result<Self, NegotiateError> {
|
||||||
|
Ok(Self {
|
||||||
|
inner: signalr::Stream::from_ws(crate::stream::Stream::open(ctx).await?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn recv(&mut self) -> Result<Event, ObservationError> {
|
||||||
|
use signalr::Message::*;
|
||||||
|
let de = |msg| -> Result<Event, ObservationError> { Err(ObservationError::Protocol(msg)) };
|
||||||
|
loop {
|
||||||
|
let msg = self.inner.recv().await?;
|
||||||
|
match &msg {
|
||||||
|
Ping => continue,
|
||||||
|
Empty | InvocationResult { .. } => info!("Skipped message: {msg:?}"),
|
||||||
|
Invocation { target, arguments } if target == "ProductUpdate" => {
|
||||||
|
if arguments.len() != 1 {
|
||||||
|
return de(msg);
|
||||||
|
};
|
||||||
|
let evt = ProductUpdate::deserialize(&arguments[0])?;
|
||||||
|
return decode_update(evt);
|
||||||
|
}
|
||||||
|
Invocation { .. } => continue,
|
||||||
|
_other => return de(msg),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub async fn subscribe(&mut self, id: &str) -> Result<(), tungstenite::Error> {
|
||||||
|
self.inner
|
||||||
|
.invoke("SubscribeWithCurrentState", json!([id, true])).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_update(update: ProductUpdate) -> Result<Event, ObservationError> {
|
||||||
|
let ProductUpdate {
|
||||||
|
data_type,
|
||||||
|
id,
|
||||||
|
mid,
|
||||||
|
timestamp,
|
||||||
|
value,
|
||||||
|
} = update;
|
||||||
|
let data = ObservationData::from_dynamic(value, data_type)?;
|
||||||
|
let obs = Observation::try_from_data(id, data);
|
||||||
|
let _ = timestamp;
|
||||||
|
Ok(Event {
|
||||||
|
charger: mid,
|
||||||
|
observation: obs,
|
||||||
|
})
|
||||||
|
}
|
||||||
+136
@@ -0,0 +1,136 @@
|
|||||||
|
use serde_json::{json, Value};
|
||||||
|
use thiserror::Error;
|
||||||
|
|
||||||
|
use crate::stream::RecvError;
|
||||||
|
|
||||||
|
/* This entire module can be rewritten in two lines when
|
||||||
|
https://github.com/serde-rs/serde/issues/745
|
||||||
|
is merged */
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum Message {
|
||||||
|
Empty,
|
||||||
|
Invocation {
|
||||||
|
target: String,
|
||||||
|
arguments: Vec<Value>,
|
||||||
|
},
|
||||||
|
InvocationResult {
|
||||||
|
id: String,
|
||||||
|
result: serde_json::Value,
|
||||||
|
},
|
||||||
|
Ping,
|
||||||
|
Other(serde_json::Value),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum ParseError {
|
||||||
|
#[error("Expecting object, received {0}")]
|
||||||
|
ExpectingObject(Value),
|
||||||
|
|
||||||
|
#[error("Missing `type` key")]
|
||||||
|
MissingTypeKey,
|
||||||
|
|
||||||
|
#[error("`type` is not a number")]
|
||||||
|
TypeNotANumber,
|
||||||
|
|
||||||
|
#[error("Unknown type {0}")]
|
||||||
|
UnknownType(u64),
|
||||||
|
|
||||||
|
#[error("Missing expected key {0}")]
|
||||||
|
MissingKey(&'static str),
|
||||||
|
|
||||||
|
#[error("Expecting string")]
|
||||||
|
ExpectingString,
|
||||||
|
|
||||||
|
#[error("Expecting array")]
|
||||||
|
ExpectingArray,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Message {
|
||||||
|
pub fn from_json(msg: Value) -> Result<Self, ParseError> {
|
||||||
|
let Some(obj) = msg.as_object() else {
|
||||||
|
return Err(ParseError::ExpectingObject(msg));
|
||||||
|
};
|
||||||
|
if obj.is_empty() {
|
||||||
|
return Ok(Message::Empty);
|
||||||
|
}
|
||||||
|
let typ = obj
|
||||||
|
.get("type")
|
||||||
|
.ok_or(ParseError::MissingTypeKey)?
|
||||||
|
.as_number()
|
||||||
|
.and_then(|n| n.as_u64())
|
||||||
|
.ok_or(ParseError::TypeNotANumber)?;
|
||||||
|
|
||||||
|
match typ {
|
||||||
|
1 => Ok(Message::Invocation {
|
||||||
|
target: obj
|
||||||
|
.get("target")
|
||||||
|
.ok_or(ParseError::MissingKey("target"))?
|
||||||
|
.as_str()
|
||||||
|
.ok_or(ParseError::ExpectingString)?
|
||||||
|
.to_owned(),
|
||||||
|
arguments: obj
|
||||||
|
.get("arguments")
|
||||||
|
.ok_or(ParseError::MissingKey("arguments"))?
|
||||||
|
.as_array()
|
||||||
|
.ok_or(ParseError::ExpectingArray)?
|
||||||
|
.to_owned(),
|
||||||
|
}),
|
||||||
|
3 => Ok(Message::InvocationResult {
|
||||||
|
id: obj
|
||||||
|
.get("invocationId")
|
||||||
|
.ok_or(ParseError::MissingKey("invocationId"))?
|
||||||
|
.as_str()
|
||||||
|
.ok_or(ParseError::ExpectingString)?
|
||||||
|
.to_owned(),
|
||||||
|
result: obj
|
||||||
|
.get("result")
|
||||||
|
.ok_or(ParseError::MissingKey("result"))?
|
||||||
|
.to_owned(),
|
||||||
|
}),
|
||||||
|
6 => Ok(Message::Ping),
|
||||||
|
_ => Ok(Message::Other(msg)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum StreamError {
|
||||||
|
#[error("Parse error: {0}")]
|
||||||
|
ParseError(#[from] ParseError),
|
||||||
|
|
||||||
|
#[error("Recv error: {0}")]
|
||||||
|
StreamError(#[from] RecvError),
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Stream {
|
||||||
|
buffer: Vec<serde_json::Value>,
|
||||||
|
ws: super::stream::Stream,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream {
|
||||||
|
pub fn from_ws(ws: super::stream::Stream) -> Self {
|
||||||
|
Self { ws, buffer: vec![] }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn recv(&mut self) -> Result<Message, StreamError> {
|
||||||
|
while self.buffer.is_empty() {
|
||||||
|
self.buffer = self.ws.recv().await?;
|
||||||
|
self.buffer.reverse();
|
||||||
|
}
|
||||||
|
|
||||||
|
let json = self.buffer.pop().unwrap();
|
||||||
|
Ok(Message::from_json(json)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn invoke(
|
||||||
|
&mut self,
|
||||||
|
target: &str,
|
||||||
|
args: serde_json::Value,
|
||||||
|
) -> Result<(), tungstenite::Error> {
|
||||||
|
self.ws.send(json!( { "arguments": args,
|
||||||
|
"invocationId": "0",
|
||||||
|
"target": target,
|
||||||
|
"type": 1} )).await
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
use super::api::{ApiError, Context};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
use serde_json::json;
|
||||||
|
use tokio::net::TcpStream;
|
||||||
|
use thiserror::Error;
|
||||||
|
//use tungstenite::{stream::MaybeTlsStream, Message, WebSocket};
|
||||||
|
use tokio_tungstenite::{MaybeTlsStream, tungstenite::Message, WebSocketStream};
|
||||||
|
use futures_util::{SinkExt,StreamExt};
|
||||||
|
|
||||||
|
const STREAM_API_NEGOTIATION_URL: &str =
|
||||||
|
"https://streams.easee.com/hubs/products/negotiate?negotiateVersion=1";
|
||||||
|
const WSS_URL: &str = "wss://streams.easee.com/hubs/products";
|
||||||
|
|
||||||
|
#[derive(Clone, Debug, Deserialize, PartialEq, PartialOrd)]
|
||||||
|
#[serde(rename_all = "camelCase")]
|
||||||
|
struct NegotiateResponse {
|
||||||
|
negotiate_version: u16,
|
||||||
|
connection_id: String,
|
||||||
|
connection_token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum NegotiateError {
|
||||||
|
#[error("API error: {0}")]
|
||||||
|
ApiError(#[from] ApiError),
|
||||||
|
|
||||||
|
#[error("WS error: {0}")]
|
||||||
|
TungsteniteError(#[from] tungstenite::Error),
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Error)]
|
||||||
|
pub enum RecvError {
|
||||||
|
#[error("Bad message type")]
|
||||||
|
BadMessageType,
|
||||||
|
|
||||||
|
#[error("Invalid json: {0}")]
|
||||||
|
InvalidJson(#[from] serde_json::Error),
|
||||||
|
|
||||||
|
#[error("WS error: {0}")]
|
||||||
|
TungsteniteError(#[from] tungstenite::Error),
|
||||||
|
|
||||||
|
#[error("End of stream")]
|
||||||
|
EndOfStream,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Stream {
|
||||||
|
sock: WebSocketStream<MaybeTlsStream<TcpStream>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stream {
|
||||||
|
pub async fn open(ctx: &mut Context) -> Result<Stream, NegotiateError> {
|
||||||
|
let r: NegotiateResponse = ctx.post_raw(STREAM_API_NEGOTIATION_URL, &()).await?;
|
||||||
|
|
||||||
|
let token = ctx.auth_token();
|
||||||
|
let wss_url = format!(
|
||||||
|
"{}?id={}&access_token={}",
|
||||||
|
WSS_URL, r.connection_token, token
|
||||||
|
);
|
||||||
|
|
||||||
|
let resp = tokio_tungstenite::connect_async(wss_url).await;
|
||||||
|
//let resp = tungstenite::client::connect(&wss_url);
|
||||||
|
|
||||||
|
if let Err(tungstenite::Error::Http(he)) = &resp {
|
||||||
|
eprintln!(
|
||||||
|
"Response: {}",
|
||||||
|
std::str::from_utf8(&he.body().as_ref().unwrap()).unwrap()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut stream = Stream { sock: resp?.0 };
|
||||||
|
stream.send(json!({ "protocol": "json", "version": 1 })).await?;
|
||||||
|
|
||||||
|
Ok(stream)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send<T: Serialize>(&mut self, msg: T) -> Result<(), tungstenite::Error> {
|
||||||
|
let mut msg = serde_json::to_string(&msg).unwrap();
|
||||||
|
msg.push('\x1E');
|
||||||
|
self.sock.send(Message::Text(msg)).await
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn recv(&mut self) -> Result<Vec<serde_json::Value>, RecvError> {
|
||||||
|
let msg = self.sock.next().await
|
||||||
|
.ok_or(RecvError::EndOfStream)??;
|
||||||
|
let Message::Text(txt) = msg else {
|
||||||
|
return Err(RecvError::BadMessageType);
|
||||||
|
};
|
||||||
|
|
||||||
|
let msgs = txt
|
||||||
|
.split_terminator('\x1E')
|
||||||
|
.filter_map(|s| serde_json::from_str(s).ok())
|
||||||
|
.collect();
|
||||||
|
|
||||||
|
Ok(msgs)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user