Compare commits
7 Commits
c43eaec771
...
b731f182be
Author | SHA1 | Date | |
---|---|---|---|
b731f182be | |||
a02ac05443 | |||
da332aebbe | |||
ec3499763b | |||
44fba534b4 | |||
2380e35754 | |||
0130c32096 |
1
.gitignore
vendored
1
.gitignore
vendored
@ -1 +1,2 @@
|
|||||||
/target
|
/target
|
||||||
|
Cargo.lock
|
||||||
|
@ -3,6 +3,13 @@ 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
|
||||||
|
|
||||||
|
60
src/api.rs
60
src/api.rs
@ -5,6 +5,7 @@ use serde_repr::Deserialize_repr;
|
|||||||
use thiserror::Error;
|
use thiserror::Error;
|
||||||
use tracing::{debug, info, instrument};
|
use tracing::{debug, info, instrument};
|
||||||
|
|
||||||
|
/// API Authentication context
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Context {
|
pub struct Context {
|
||||||
auth_header: String,
|
auth_header: String,
|
||||||
@ -12,10 +13,10 @@ pub struct Context {
|
|||||||
token_expiration: Instant,
|
token_expiration: Instant,
|
||||||
}
|
}
|
||||||
|
|
||||||
const API_BASE: &'static str = "https://api.easee.com/api/";
|
const API_BASE: &str = "https://api.easee.com/api/";
|
||||||
const REFRESH_TOKEN_DELAY: Duration = Duration::from_secs(600);
|
const REFRESH_TOKEN_DELAY: Duration = Duration::from_secs(600);
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Clone,Copy,Debug,Eq,Ord,PartialEq,PartialOrd)]
|
||||||
pub struct NaiveDateTime(pub chrono::NaiveDateTime);
|
pub struct NaiveDateTime(pub chrono::NaiveDateTime);
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for NaiveDateTime {
|
impl<'de> Deserialize<'de> for NaiveDateTime {
|
||||||
@ -29,7 +30,7 @@ impl<'de> Deserialize<'de> for NaiveDateTime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Clone,Copy,Debug,Eq,Ord,PartialEq,PartialOrd)]
|
||||||
pub struct UtcDateTime(pub chrono::DateTime<chrono::Utc>);
|
pub struct UtcDateTime(pub chrono::DateTime<chrono::Utc>);
|
||||||
|
|
||||||
impl<'de> Deserialize<'de> for UtcDateTime {
|
impl<'de> Deserialize<'de> for UtcDateTime {
|
||||||
@ -44,7 +45,7 @@ impl<'de> Deserialize<'de> for UtcDateTime {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Clone,Debug,Deserialize,Eq,Ord,PartialEq,PartialOrd)]
|
||||||
#[serde(rename_all="camelCase")]
|
#[serde(rename_all="camelCase")]
|
||||||
pub struct Charger {
|
pub struct Charger {
|
||||||
pub id: String,
|
pub id: String,
|
||||||
@ -56,16 +57,17 @@ pub struct Charger {
|
|||||||
pub level_of_access: u32,
|
pub level_of_access: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize_repr, Debug)]
|
#[derive(Clone,Copy,Debug,Deserialize_repr,Eq,Ord,PartialEq,PartialOrd)]
|
||||||
#[repr(u8)]
|
#[repr(u8)]
|
||||||
pub enum ChargerOpMode {
|
pub enum ChargerOpMode {
|
||||||
Zero = 0,
|
Zero = 0,
|
||||||
One = 1,
|
One = 1,
|
||||||
Paused = 2,
|
Paused = 2,
|
||||||
Charging = 3,
|
Charging = 3,
|
||||||
|
Finished = 4,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[derive(Clone,Debug,Deserialize,PartialEq,PartialOrd)]
|
||||||
#[serde(rename_all="camelCase")]
|
#[serde(rename_all="camelCase")]
|
||||||
pub struct ChargerState {
|
pub struct ChargerState {
|
||||||
pub smart_charging: bool,
|
pub smart_charging: bool,
|
||||||
@ -139,7 +141,7 @@ pub struct ChargerState {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug,Deserialize)]
|
#[derive(Clone,Debug,Deserialize,PartialEq,PartialOrd)]
|
||||||
#[serde(rename_all = "camelCase")]
|
#[serde(rename_all = "camelCase")]
|
||||||
pub struct ChargingSession {
|
pub struct ChargingSession {
|
||||||
pub charger_id: Option<String>,
|
pub charger_id: Option<String>,
|
||||||
@ -166,7 +168,7 @@ pub struct Address {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug,Deserialize)]
|
#[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>,
|
||||||
@ -178,7 +180,7 @@ pub struct Site {
|
|||||||
pub installer_alias: Option<String>
|
pub installer_alias: Option<String>
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Deserialize, Debug)]
|
#[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,
|
||||||
@ -190,23 +192,35 @@ pub struct LoginResponse {
|
|||||||
|
|
||||||
#[derive(Debug,Error)]
|
#[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),
|
Ureq(#[source] Box<ureq::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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl From<ureq::Error> for ApiError {
|
||||||
|
fn from(value: ureq::Error) -> Self {
|
||||||
|
ApiError::Ureq(Box::new(value))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
trait JsonExplicitError {
|
trait JsonExplicitError {
|
||||||
|
/// Explicitely report the received JSON object we failed to parse
|
||||||
fn into_json_with_error<T: DeserializeOwned>(self) -> Result<T, ApiError>;
|
fn into_json_with_error<T: DeserializeOwned>(self) -> Result<T, ApiError>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -220,6 +234,7 @@ impl JsonExplicitError for ureq::Response {
|
|||||||
|
|
||||||
impl Context {
|
impl Context {
|
||||||
|
|
||||||
|
/// Build a context from provided acess tokens
|
||||||
pub fn from_tokens(access_token: &str, refresh_token: String, expires_in: u32) -> Self {
|
pub fn from_tokens(access_token: &str, refresh_token: String, expires_in: u32) -> Self {
|
||||||
Self { auth_header: format!("Bearer {}", access_token),
|
Self { auth_header: format!("Bearer {}", access_token),
|
||||||
refresh_token,
|
refresh_token,
|
||||||
@ -230,6 +245,7 @@ impl Context {
|
|||||||
Self::from_tokens(&resp.access_token, resp.refresh_token, resp.expires_in)
|
Self::from_tokens(&resp.access_token, resp.refresh_token, resp.expires_in)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Retrieve access tokens online, by logging in with the provided credentials
|
||||||
pub fn from_login(user: &str, password: &str) -> Result<Self, ApiError> {
|
pub fn from_login(user: &str, password: &str) -> Result<Self, ApiError> {
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
#[serde(rename_all="camelCase")]
|
#[serde(rename_all="camelCase")]
|
||||||
@ -244,6 +260,7 @@ impl Context {
|
|||||||
Ok(Self::from_login_response(resp))
|
Ok(Self::from_login_response(resp))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Check if the token has reached its expiration date
|
||||||
fn check_expired(&mut self) -> Result<(), ApiError> {
|
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");
|
||||||
@ -252,6 +269,7 @@ impl Context {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Use the refresh token to refresh credentials
|
||||||
pub fn refresh_token(&mut self) -> Result<(), ApiError> {
|
pub fn refresh_token(&mut self) -> Result<(), ApiError> {
|
||||||
#[derive(Serialize)]
|
#[derive(Serialize)]
|
||||||
#[serde(rename_all="camelCase")]
|
#[serde(rename_all="camelCase")]
|
||||||
@ -262,7 +280,7 @@ impl Context {
|
|||||||
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 = ureq::post(&url)
|
||||||
.set("Content-type", "application/json")
|
.set("Content-type", "application/json")
|
||||||
.send_json(¶ms)?
|
.send_json(params)?
|
||||||
.into_json_with_error()?;
|
.into_json_with_error()?;
|
||||||
|
|
||||||
*self = Self::from_login_response(resp);
|
*self = Self::from_login_response(resp);
|
||||||
@ -270,10 +288,12 @@ impl Context {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// List all sites available to the user
|
||||||
pub fn sites(&mut self) -> Result<Vec<Site>, ApiError> {
|
pub fn sites(&mut self) -> Result<Vec<Site>, ApiError> {
|
||||||
self.get("sites")
|
self.get("sites")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// List all chargers available to the user
|
||||||
pub fn chargers(&mut self) -> Result<Vec<Charger>, ApiError> {
|
pub fn chargers(&mut self) -> Result<Vec<Charger>, ApiError> {
|
||||||
self.get("chargers")
|
self.get("chargers")
|
||||||
}
|
}
|
||||||
@ -293,13 +313,16 @@ impl Context {
|
|||||||
resp = req.call()?
|
resp = req.call()?
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(resp.into_json_with_error()?)
|
resp.into_json_with_error()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn maybe_get<T: DeserializeOwned>(&mut self, path: &str) -> Result<Option<T>, ApiError> {
|
fn maybe_get<T: DeserializeOwned>(&mut self, path: &str) -> Result<Option<T>, ApiError> {
|
||||||
match self.get(path) {
|
match self.get(path) {
|
||||||
Ok(r) => Ok(Some(r)),
|
Ok(r) => Ok(Some(r)),
|
||||||
Err(ApiError::Ureq(ureq::Error::Status(404, _))) => Ok(None),
|
Err(ApiError::Ureq(e)) => match &*e {
|
||||||
|
ureq::Error::Status(404, _ ) => Ok(None),
|
||||||
|
_ => Err(ApiError::Ureq(e))
|
||||||
|
},
|
||||||
Err(other) => Err(other)
|
Err(other) => Err(other)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -318,39 +341,48 @@ impl Context {
|
|||||||
resp = req.send_json(params)?
|
resp = req.send_json(params)?
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(resp.into_json_with_error()?)
|
resp.into_json_with_error()
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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 {
|
||||||
|
/// Read all energy meters from the given site
|
||||||
pub fn lifetime_energy(&self, ctx: &mut Context) -> Result<Vec<MeterReading>, ApiError> {
|
pub fn lifetime_energy(&self, ctx: &mut Context) -> Result<Vec<MeterReading>, ApiError> {
|
||||||
ctx.get(&format!("sites/{}/energy", self.id))
|
ctx.get(&format!("sites/{}/energy", self.id))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Charger {
|
impl Charger {
|
||||||
|
/// Enable "smart charging" on the charger. This just turns the LED blue, and disables basic charging plans.
|
||||||
pub fn enable_smart_charging(&self, ctx: &mut Context) -> Result<(), ApiError> {
|
pub 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, &())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Read the state of a charger
|
||||||
pub fn state(&self, ctx: &mut Context) -> Result<ChargerState, ApiError> {
|
pub 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Read info about the ongoing charging session
|
||||||
pub fn ongoing_session(&self, ctx: &mut Context) -> Result<Option<ChargingSession>, ApiError> {
|
pub fn ongoing_session(&self, ctx: &mut Context) -> Result<Option<ChargingSession>, ApiError> {
|
||||||
ctx.maybe_get(&format!("chargers/{}/sessions/ongoing", &self.id))
|
ctx.maybe_get(&format!("chargers/{}/sessions/ongoing", &self.id))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Read info about the last charging session (not including ongoing one)
|
||||||
pub fn latest_session(&self, ctx: &mut Context) -> Result<Option<ChargingSession>, ApiError> {
|
pub fn latest_session(&self, ctx: &mut Context) -> Result<Option<ChargingSession>, ApiError> {
|
||||||
ctx.maybe_get(&format!("chargers/{}/sessions/latest", &self.id))
|
ctx.maybe_get(&format!("chargers/{}/sessions/latest", &self.id))
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user