Compare commits

...

14 Commits

Author SHA1 Message Date
max a4eb9dceba Update README 2024-08-29 15:02:36 +02:00
max 17a3cf1018 Convert to async 2024-08-29 15:00:27 +02:00
max 0a5891b5be Add LedMode 2024-08-27 14:33:46 +02:00
max d1a5666d18 Add a few observables 2024-08-26 22:21:28 +02:00
max 4a4dea12ce Implement more observation codes 2024-08-26 17:43:45 +02:00
max 7cdc180a6c Fix handling of booleans in SignalR 2024-08-26 14:35:31 +02:00
max 44d9f9bb41 API tweaks 2024-08-25 13:23:37 +02:00
max 7881799e84 Revert incorrect API change 2024-08-21 22:07:50 +02:00
max bc1a15f27c Add missing numerical codes for charger op mode 2024-08-21 21:49:48 +02:00
max f2c5b86909 Site details API 2024-08-21 16:09:16 +02:00
max dfd87f2af1 Add a representation for Triphase values 2024-08-21 15:38:54 +02:00
max 7f93f2d0b7 Report back failing string on parse error 2024-08-19 20:27:47 +02:00
max 6b6df9eaca Implement Circuits and Dynamic current APIs 2024-08-13 16:10:40 +02:00
max 4470f281fc Skip logging of ping messages, cleanup 2024-08-13 16:10:02 +02:00
7 changed files with 340 additions and 125 deletions
+4 -1
View File
@@ -15,10 +15,13 @@ categories = ["api-bindings"]
[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" 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"
tungstenite = { version = "0.23.0", optional = true, features = ["rustls-tls-native-roots"] } tungstenite = { version = "0.23.0", optional = true, features = ["rustls-tls-native-roots"] }
ureq = { version = "2.10.0", features = ["json"] }
+4 -10
View File
@@ -6,24 +6,18 @@ Work in progress.
- Authn/z - Authn/z
- [x] Authentication and token retrieval - [x] Authentication and token retrieval
- [ ] Persistence of tokens - [x] Persistence of tokens
- Core functionality - Core functionality
- [x] Enumerate sites and chargers - [x] Enumerate sites and chargers
- [x] Read energy meter - [x] Read energy meter
- [x] Read charger status - [x] Read charger status
- [ ] Control charging (start/pause/resume/stop) - [x] Control charging (start/pause/resume/stop)
- [ ] Control dynamic current limits - [x] Control dynamic current limits
- Event stream - Event stream
- [x] Websocket connection (raw SignalR messages) - [x] Websocket connection (raw SignalR messages)
- [ ] Event decoding - [x] Event decoding
- Ergonomics - Ergonomics
- [ ] Enums for protocol constants - [ ] Enums for protocol constants
- [ ] Proper SignalR support with Tokio - [ ] Proper SignalR support with Tokio
[1]: https://easee.com [1]: https://easee.com
+229 -79
View File
@@ -1,6 +1,5 @@
use std::{ use std::{
io, io, ops::{Add, Mul, Sub}, time::{Duration, Instant, SystemTime, UNIX_EPOCH}
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
}; };
use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize}; use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize};
@@ -8,11 +7,14 @@ use serde_repr::Deserialize_repr;
use thiserror::Error; use thiserror::Error;
use tracing::{debug, info, instrument}; use tracing::{debug, info, instrument};
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)>>, on_refresh: Option<Box<dyn FnMut(&mut Self) + Send>>,
client: reqwest::Client,
} }
impl std::fmt::Debug for Context { impl std::fmt::Debug for Context {
@@ -55,6 +57,66 @@ impl<'de> Deserialize<'de> for UtcDateTime {
} }
} }
#[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)] #[derive(Clone, Debug, Deserialize, Eq, Ord, PartialEq, PartialOrd)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct Charger { pub struct Charger {
@@ -77,6 +139,8 @@ pub enum ChargerOpMode {
Finished = 4, Finished = 4,
Error = 5, Error = 5,
Ready = 6, Ready = 6,
AwaitingAuthentication = 7,
Deauthenticating = 8,
} }
#[derive(Clone, Copy, Debug, Deserialize_repr, Eq, Ord, PartialEq, PartialOrd)] #[derive(Clone, Copy, Debug, Deserialize_repr, Eq, Ord, PartialEq, PartialOrd)]
@@ -204,6 +268,28 @@ pub struct Site {
pub installer_alias: Option<String>, pub installer_alias: Option<String>,
} }
#[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)] #[derive(Clone, Debug, Deserialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
pub struct LoginResponse { pub struct LoginResponse {
@@ -231,7 +317,7 @@ pub enum ApiError {
/// HTTP call failed (404, etc) /// HTTP call failed (404, etc)
#[error("ureq")] #[error("ureq")]
Ureq(#[source] Box<ureq::Error>), HTTP(#[source] Box<reqwest::Error>),
/// HTTP call succeeded but the returned JSON document didn't match the expected format /// 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}")]
@@ -249,20 +335,20 @@ pub enum ApiError {
InvalidID(String), InvalidID(String),
} }
impl From<ureq::Error> for ApiError { impl From<reqwest::Error> for ApiError {
fn from(value: ureq::Error) -> Self { fn from(value: reqwest::Error) -> Self {
ApiError::Ureq(Box::new(value)) ApiError::HTTP(Box::new(value))
} }
} }
trait JsonExplicitError { trait JsonExplicitError {
/// Explicitely report the received JSON object we failed to parse /// Explicitely report the received JSON object we failed to parse
fn into_json_with_error<T: DeserializeOwned>(self) -> Result<T, ApiError>; 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))
} }
@@ -278,12 +364,13 @@ pub enum TokenParseError {
} }
impl Context { impl Context {
fn from_login_response(resp: LoginResponse) -> Self { fn from_login_response(resp: LoginResponse, client: reqwest::Client) -> Self {
Self { Self {
auth_header: format!("Bearer {}", &resp.access_token), auth_header: format!("Bearer {}", &resp.access_token),
refresh_token: resp.refresh_token, refresh_token: resp.refresh_token,
token_expiration: (Instant::now() + Duration::from_secs(resp.expires_in as u64)), token_expiration: (Instant::now() + Duration::from_secs(resp.expires_in as u64)),
on_refresh: None, on_refresh: None,
client,
} }
} }
@@ -304,10 +391,11 @@ impl Context {
refresh_token: refresh.to_owned(), refresh_token: refresh.to_owned(),
token_expiration, token_expiration,
on_refresh: None, on_refresh: None,
client: reqwest::Client::new(),
}) })
} }
pub fn on_refresh<F: FnMut(&mut Self) + 'static>(mut self, on_refresh: F) -> Self { 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.on_refresh = Some(Box::new(on_refresh));
self self
} }
@@ -325,7 +413,7 @@ impl Context {
} }
/// Retrieve access tokens online, by logging in with the provided credentials /// Retrieve access tokens online, by logging in with the provided credentials
pub fn from_login(user: &str, password: &str) -> Result<Self, ApiError> { 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> { struct Params<'t> {
@@ -333,23 +421,26 @@ impl Context {
password: &'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 { .json(&Params {
user_name: user, user_name: user,
password, password,
})? })
.into_json_with_error()?; .send().await?
.into_json_with_error().await?;
Ok(Self::from_login_response(resp)) Ok(Self::from_login_response(resp, client))
} }
/// Check if the token has reached its expiration date /// Check if the token has reached its expiration date
fn check_expired(&mut self) -> Result<(), ApiError> { 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(())
} }
@@ -359,7 +450,7 @@ impl Context {
} }
/// Use the refresh token to refresh credentials /// Use the refresh token to refresh credentials
pub fn refresh_token(&mut self) -> Result<(), ApiError> { pub async fn refresh_token(&mut self) -> Result<(), ApiError> {
#[derive(Serialize)] #[derive(Serialize)]
#[serde(rename_all = "camelCase")] #[serde(rename_all = "camelCase")]
struct Params<'t> { struct Params<'t> {
@@ -371,88 +462,121 @@ impl Context {
refresh_token: &self.refresh_token, 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(params)? .json(&params)
.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(())
} }
/// List all sites available to the user /// List all sites available to the user
pub fn sites(&mut self) -> Result<Vec<Site>, ApiError> { pub async fn sites(&mut self) -> Result<Vec<Site>, ApiError> {
self.get("sites") self.get("sites").await
}
pub async fn site(&mut self, id: i32) -> Result<SiteDetails, ApiError> {
self.get(&format!("sites/{id}")).await
} }
/// List all chargers available to the user /// List all chargers available to the user
pub fn chargers(&mut self) -> Result<Vec<Charger>, ApiError> { pub async fn chargers(&mut self) -> Result<Vec<Charger>, ApiError> {
self.get("chargers") self.get("chargers").await
} }
pub fn charger(&mut self, id: &str) -> Result<Charger, ApiError> { pub async fn charger(&mut self, id: &str) -> Result<Charger, ApiError> {
if !id.chars().all(char::is_alphanumeric) { if !id.chars().all(char::is_alphanumeric) {
return Err(ApiError::InvalidID(id.to_owned())); return Err(ApiError::InvalidID(id.to_owned()));
} }
self.get(&format!("chargers/{}", id)) 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"),
&current,
).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?
} }
resp.into_json_with_error() resp.into_json_with_error().await
} }
fn maybe_get<T: DeserializeOwned>(&mut self, path: &str) -> Result<Option<T>, ApiError> { async fn maybe_get<T: DeserializeOwned>(&mut self, path: &str) -> Result<Option<T>, ApiError> {
match self.get(path) { match self.get(path).await {
Ok(r) => Ok(Some(r)), Ok(r) => Ok(Some(r)),
Err(ApiError::Ureq(e)) => match &*e { Err(ApiError::HTTP(e)) if e.status() == Some(StatusCode::NOT_FOUND)=> Ok(None),
ureq::Error::Status(404, _) => Ok(None),
_ => Err(ApiError::Ureq(e)),
},
Err(other) => Err(other), Err(other) => Err(other),
} }
} }
pub(crate) fn post<T: DeserializeOwned, P: Serialize>( pub(crate) async fn post<T: DeserializeOwned, P: Serialize>(
&mut self, &mut self,
path: &str, path: &str,
params: &P, params: &P,
) -> Result<T, ApiError> { ) -> Result<T, ApiError> {
let url: String = format!("{}{}", API_BASE, path); let url: String = format!("{}{}", API_BASE, path);
self.post_raw(&url, params) self.post_raw(&url, params).await
} }
pub(crate) fn post_raw<T: DeserializeOwned, P: Serialize>( pub(crate) async fn post_raw<T: DeserializeOwned, P: Serialize>(
&mut self, &mut self,
url: &str, url: &str,
params: &P, params: &P,
) -> Result<T, ApiError> { ) -> Result<T, ApiError> {
self.check_expired()?; self.check_expired().await?;
let req = ureq::post(url) let req = self.client.post(url)
.set("Accept", "application/json") .header("Accept", "application/json")
.set("Authorization", &self.auth_header); .header("Authorization", &self.auth_header)
.json(params);
let mut resp = req.clone().send_json(params)?; let mut resp = req
.try_clone().unwrap()
.send().await?;
if resp.status() == 401 { if resp.status() == 401 {
self.refresh_token()?; self.refresh_token().await?;
resp = req.send_json(params)? resp = req.send().await?
} }
resp.into_json_with_error() resp.into_json_with_error().await
} }
} }
@@ -469,55 +593,77 @@ pub struct MeterReading {
impl Site { impl Site {
/// Read all energy meters from the given site /// Read all energy meters from the given site
pub fn lifetime_energy(&self, ctx: &mut Context) -> Result<Vec<MeterReading>, ApiError> { pub async 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)).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(), &current).await
} }
} }
impl Charger { impl Charger {
/// Enable "smart charging" on the charger. This just turns the LED blue, and disables basic charging plans. /// 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 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
} }
/// Read the state of a charger /// Read the state of a charger
pub fn state(&self, ctx: &mut Context) -> Result<ChargerState, ApiError> { 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 /// Read info about the ongoing charging session
pub fn ongoing_session(&self, ctx: &mut Context) -> Result<Option<ChargingSession>, ApiError> { pub async 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)).await
} }
/// Read info about the last charging session (not including ongoing one) /// Read info about the last charging session (not including ongoing one)
pub fn latest_session(&self, ctx: &mut Context) -> Result<Option<ChargingSession>, ApiError> { pub async 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)).await
} }
fn command(&self, ctx: &mut Context, command: &str) -> Result<CommandReply, ApiError> { async fn command(&self, ctx: &mut Context, command: &str) -> Result<CommandReply, ApiError> {
ctx.post(&format!("chargers/{}/commands/{}", self.id, command), &()) ctx.post(&format!("chargers/{}/commands/{}", self.id, command), &()).await
} }
pub fn start(&self, ctx: &mut Context) -> Result<(), ApiError> { pub async fn start(&self, ctx: &mut Context) -> Result<(), ApiError> {
self.command(ctx, "start_charging")?; self.command(ctx, "start_charging").await?;
Ok(()) Ok(())
} }
pub fn pause(&self, ctx: &mut Context) -> Result<(), ApiError> { pub async fn pause(&self, ctx: &mut Context) -> Result<(), ApiError> {
self.command(ctx, "pause_charging")?; self.command(ctx, "pause_charging").await?;
Ok(()) Ok(())
} }
pub fn resume(&self, ctx: &mut Context) -> Result<(), ApiError> { pub async fn resume(&self, ctx: &mut Context) -> Result<(), ApiError> {
self.command(ctx, "resume_charging")?; self.command(ctx, "resume_charging").await?;
Ok(()) Ok(())
} }
pub fn stop(&self, ctx: &mut Context) -> Result<(), ApiError> { pub async fn stop(&self, ctx: &mut Context) -> Result<(), ApiError> {
self.command(ctx, "stop_charging")?; self.command(ctx, "stop_charging").await?;
Ok(()) Ok(())
} }
} }
@@ -529,11 +675,15 @@ mod test {
use super::Context; use super::Context;
#[test] #[test]
fn token_save() { fn token_save() {
let client = reqwest::Client::new();
let ctx = Context { let ctx = Context {
auth_header: "Bearer aaaaaaa0".to_owned(), auth_header: "Bearer aaaaaaa0".to_owned(),
refresh_token: "abcdef".to_owned(), refresh_token: "abcdef".to_owned(),
token_expiration: Instant::now() + Duration::from_secs(1234), token_expiration: Instant::now() + Duration::from_secs(1234),
on_refresh: None, on_refresh: None,
client: client.clone(),
}; };
let saved = ctx.save(); let saved = ctx.save();
+1
View File
@@ -6,4 +6,5 @@ pub mod stream;
#[cfg(feature = "tungstenite")] #[cfg(feature = "tungstenite")]
pub mod signalr; pub mod signalr;
#[cfg(feature = "tungstenite")]
pub mod observation; pub mod observation;
+80 -20
View File
@@ -1,9 +1,9 @@
use serde::{de::IntoDeserializer, Deserialize}; use serde::{de::{DeserializeOwned, IntoDeserializer}, Deserialize};
use serde_json::json;
use serde_repr::Deserialize_repr; use serde_repr::Deserialize_repr;
use std::num::{ParseFloatError, ParseIntError}; use std::num::{ParseFloatError, ParseIntError};
use thiserror::Error; use thiserror::Error;
use tracing::info; use tracing::info;
use ureq::json;
use crate::{ use crate::{
api::{ChargerOpMode, Context, OutputPhase, UtcDateTime}, api::{ChargerOpMode, Context, OutputPhase, UtcDateTime},
@@ -73,23 +73,41 @@ pub enum ObservationData {
#[derive(Error, Debug)] #[derive(Error, Debug)]
pub enum ParseError { pub enum ParseError {
#[error("integer: {0}")] #[error("integer `{0}`: {1}")]
Integer(#[from] ParseIntError), Integer(String, ParseIntError),
#[error("double: {0}")] #[error("double `{0}: {1}")]
Double(#[from] ParseFloatError), Double(String, ParseFloatError),
} }
impl ObservationData { impl ObservationData {
fn from_dynamic(value: String, data_type: DataType) -> Result<ObservationData, ParseError> { fn from_dynamic(value: String, data_type: DataType) -> Result<ObservationData, ParseError> {
Ok(match data_type { Ok(match data_type {
DataType::Boolean => ObservationData::Boolean(value.parse::<i64>()? != 0), DataType::Boolean => ObservationData::Boolean(
DataType::Double => ObservationData::Double(value.parse()?), match &*value {
DataType::Integer => ObservationData::Integer(value.parse()?), "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), DataType::String => ObservationData::String(value),
}) })
} }
/*
fn dynamic_type(&self) -> DataType { fn dynamic_type(&self) -> DataType {
match self { match self {
ObservationData::Boolean(_) => DataType::Boolean, ObservationData::Boolean(_) => DataType::Boolean,
@@ -98,6 +116,7 @@ impl ObservationData {
ObservationData::String(_) => DataType::String, ObservationData::String(_) => DataType::String,
} }
} }
*/
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
@@ -152,28 +171,43 @@ pub enum Observation {
SelfTestDetails(String), SelfTestDetails(String),
WifiEvent(i64), WifiEvent(i64),
ChargerOfflineReason(i64), ChargerOfflineReason(i64),
CircuitMaxCurrent { phase: u8, amperes: i64 }, CircuitMaxCurrent { phase: u8, amperes: f64 },
SiteID(String), SiteID(String),
IsEnabled(bool), IsEnabled(bool),
Temperature(i64), Temperature(i64),
TriplePhase(bool), TriplePhase(bool),
DynamicChargerCurrent(f64), DynamicChargerCurrent(f64),
CircuitTotalCurrent { phase: u8, amperes: f64 },
ICCID(String), ICCID(String),
MobileNetworkOperator(String), MobileNetworkOperator(String),
ReasonForNoCurrent(ReasonForNoCurrent), ReasonForNoCurrent(ReasonForNoCurrent),
LocalPreauthEnabled(bool),
LocalOfflineAuthEnabled(bool),
AllowOfflineTxUnknownId(bool),
PilotMode(PilotMode), PilotMode(PilotMode),
SmartCharging(bool), SmartCharging(bool),
CableLocked(bool), CableLocked(bool),
CableRating(f64), CableRating(f64),
LedMode(i64),
UserId(String), UserId(String),
ChargerOpMode(ChargerOpMode), ChargerOpMode(ChargerOpMode),
IntCurrent { pin: InputPin, current: f64 }, IntCurrent { pin: InputPin, current: f64 },
IntVoltage { pins: (InputPin, InputPin), voltage: f64 },
ActiveOutputPhase(OutputPhase),
MaximumTemperature(i64),
TotalPower(f64), TotalPower(f64),
EnergyPerHour(f64), EnergyPerHour(f64),
LifetimeEnergy(f64), LifetimeEnergy(f64),
LifetimeRelaySwitches(i64),
LifetimeHours(i64),
Unknown { code: u16, value: ObservationData }, Unknown { code: u16, value: ObservationData },
} }
@@ -191,6 +225,10 @@ fn op_mode_from_int(mode: i64) -> ChargerOpMode {
} }
} }
fn deserialize_i64<T: DeserializeOwned>(value: i64) -> Option<T> {
T::deserialize(<i64 as IntoDeserializer<serde::de::value::Error>>::into_deserializer(value)).ok()
}
impl Observation { impl Observation {
fn try_from_data(code: u16, data: ObservationData) -> Observation { fn try_from_data(code: u16, data: ObservationData) -> Observation {
use InputPin::*; use InputPin::*;
@@ -201,15 +239,19 @@ impl Observation {
(2, String(details)) => SelfTestDetails(details), (2, String(details)) => SelfTestDetails(details),
(10, Integer(wifi)) => WifiEvent(wifi), (10, Integer(wifi)) => WifiEvent(wifi),
(11, Integer(reason)) => ChargerOfflineReason(reason), (11, Integer(reason)) => ChargerOfflineReason(reason),
(22, Integer(amperes)) => CircuitMaxCurrent { phase: 1, amperes }, (22, Double(amperes)) => CircuitMaxCurrent { phase: 1, amperes },
(23, Integer(amperes)) => CircuitMaxCurrent { phase: 2, amperes }, (23, Double(amperes)) => CircuitMaxCurrent { phase: 2, amperes },
(24, Integer(amperes)) => CircuitMaxCurrent { phase: 3, amperes }, (24, Double(amperes)) => CircuitMaxCurrent { phase: 3, amperes },
(26, String(site)) => SiteID(site), (26, String(site)) => SiteID(site),
(31, Boolean(enabled)) => IsEnabled(enabled), (31, Boolean(enabled)) => IsEnabled(enabled),
(32, Integer(temperature)) => Temperature(temperature), (32, Integer(temperature)) => Temperature(temperature),
(38, Integer(1)) => TriplePhase(false), (38, Integer(1)) => TriplePhase(false),
(38, Integer(3)) => TriplePhase(true), (38, Integer(3)) => TriplePhase(true),
(46, Integer(mode)) => LedMode(mode),
(48, Double(current)) => DynamicChargerCurrent(current), (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), (81, String(iccid)) => ICCID(iccid),
(84, String(operator)) => MobileNetworkOperator(operator), (84, String(operator)) => MobileNetworkOperator(operator),
(96, Integer(reason)) => ReasonForNoCurrent(self::ReasonForNoCurrent(reason as u16)), (96, Integer(reason)) => ReasonForNoCurrent(self::ReasonForNoCurrent(reason as u16)),
@@ -219,11 +261,28 @@ impl Observation {
(104, Double(amps)) => CableRating(amps), (104, Double(amps)) => CableRating(amps),
(107, String(tok_rev)) => UserId(tok_rev.chars().rev().collect()), (107, String(tok_rev)) => UserId(tok_rev.chars().rev().collect()),
(109, Integer(mode)) => ChargerOpMode(op_mode_from_int(mode)), (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), (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 }, (182, Double(current)) => IntCurrent { pin: T2, current },
(183, Double(current)) => IntCurrent { pin: T3, current }, (183, Double(current)) => IntCurrent { pin: T3, current },
(184, Double(current)) => IntCurrent { pin: T4, current }, (184, Double(current)) => IntCurrent { pin: T4, current },
(185, Double(current)) => IntCurrent { pin: T5, 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 }, (code, value) => Unknown { code, value },
} }
@@ -266,19 +325,20 @@ struct ProductUpdate {
} }
impl Stream { impl Stream {
pub fn from_context(ctx: &mut Context) -> Result<Self, NegotiateError> { pub async fn from_context(ctx: &mut Context) -> Result<Self, NegotiateError> {
Ok(Self { Ok(Self {
inner: signalr::Stream::from_ws(crate::stream::Stream::open(ctx)?), inner: signalr::Stream::from_ws(crate::stream::Stream::open(ctx).await?),
}) })
} }
pub fn recv(&mut self) -> Result<Event, ObservationError> { pub async fn recv(&mut self) -> Result<Event, ObservationError> {
use signalr::Message::*; use signalr::Message::*;
let de = |msg| -> Result<Event, ObservationError> { Err(ObservationError::Protocol(msg)) }; let de = |msg| -> Result<Event, ObservationError> { Err(ObservationError::Protocol(msg)) };
loop { loop {
let msg = self.inner.recv()?; let msg = self.inner.recv().await?;
match &msg { match &msg {
Empty | Ping | InvocationResult { .. } => info!("Skipped message: {msg:?}"), Ping => continue,
Empty | InvocationResult { .. } => info!("Skipped message: {msg:?}"),
Invocation { target, arguments } if target == "ProductUpdate" => { Invocation { target, arguments } if target == "ProductUpdate" => {
if arguments.len() != 1 { if arguments.len() != 1 {
return de(msg); return de(msg);
@@ -291,9 +351,9 @@ impl Stream {
} }
} }
} }
pub fn subscribe(&mut self, id: &str) -> Result<(), tungstenite::Error> { pub async fn subscribe(&mut self, id: &str) -> Result<(), tungstenite::Error> {
self.inner self.inner
.invoke("SubscribeWithCurrentState", json!([id, true])) .invoke("SubscribeWithCurrentState", json!([id, true])).await
} }
} }
+4 -4
View File
@@ -113,9 +113,9 @@ impl Stream {
Self { ws, buffer: vec![] } Self { ws, buffer: vec![] }
} }
pub fn recv(&mut self) -> Result<Message, StreamError> { pub async fn recv(&mut self) -> Result<Message, StreamError> {
while self.buffer.is_empty() { while self.buffer.is_empty() {
self.buffer = self.ws.recv()?; self.buffer = self.ws.recv().await?;
self.buffer.reverse(); self.buffer.reverse();
} }
@@ -123,7 +123,7 @@ impl Stream {
Ok(Message::from_json(json)?) Ok(Message::from_json(json)?)
} }
pub fn invoke( pub async fn invoke(
&mut self, &mut self,
target: &str, target: &str,
args: serde_json::Value, args: serde_json::Value,
@@ -131,6 +131,6 @@ impl Stream {
self.ws.send(json!( { "arguments": args, self.ws.send(json!( { "arguments": args,
"invocationId": "0", "invocationId": "0",
"target": target, "target": target,
"type": 1} )) "type": 1} )).await
} }
} }
+18 -11
View File
@@ -1,9 +1,11 @@
use super::api::{ApiError, Context}; use super::api::{ApiError, Context};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use serde_json::json; use serde_json::json;
use std::net::TcpStream; use tokio::net::TcpStream;
use thiserror::Error; use thiserror::Error;
use tungstenite::{stream::MaybeTlsStream, Message, WebSocket}; //use tungstenite::{stream::MaybeTlsStream, Message, WebSocket};
use tokio_tungstenite::{MaybeTlsStream, tungstenite::Message, WebSocketStream};
use futures_util::{SinkExt,StreamExt};
const STREAM_API_NEGOTIATION_URL: &str = const STREAM_API_NEGOTIATION_URL: &str =
"https://streams.easee.com/hubs/products/negotiate?negotiateVersion=1"; "https://streams.easee.com/hubs/products/negotiate?negotiateVersion=1";
@@ -36,15 +38,18 @@ pub enum RecvError {
#[error("WS error: {0}")] #[error("WS error: {0}")]
TungsteniteError(#[from] tungstenite::Error), TungsteniteError(#[from] tungstenite::Error),
#[error("End of stream")]
EndOfStream,
} }
pub struct Stream { pub struct Stream {
sock: WebSocket<MaybeTlsStream<TcpStream>>, sock: WebSocketStream<MaybeTlsStream<TcpStream>>,
} }
impl Stream { impl Stream {
pub fn open(ctx: &mut Context) -> Result<Stream, NegotiateError> { pub async fn open(ctx: &mut Context) -> Result<Stream, NegotiateError> {
let r: NegotiateResponse = ctx.post_raw(STREAM_API_NEGOTIATION_URL, &())?; let r: NegotiateResponse = ctx.post_raw(STREAM_API_NEGOTIATION_URL, &()).await?;
let token = ctx.auth_token(); let token = ctx.auth_token();
let wss_url = format!( let wss_url = format!(
@@ -52,7 +57,8 @@ impl Stream {
WSS_URL, r.connection_token, token WSS_URL, r.connection_token, token
); );
let resp = tungstenite::client::connect(&wss_url); let resp = tokio_tungstenite::connect_async(wss_url).await;
//let resp = tungstenite::client::connect(&wss_url);
if let Err(tungstenite::Error::Http(he)) = &resp { if let Err(tungstenite::Error::Http(he)) = &resp {
eprintln!( eprintln!(
@@ -62,19 +68,20 @@ impl Stream {
} }
let mut stream = Stream { sock: resp?.0 }; let mut stream = Stream { sock: resp?.0 };
stream.send(json!({ "protocol": "json", "version": 1 }))?; stream.send(json!({ "protocol": "json", "version": 1 })).await?;
Ok(stream) Ok(stream)
} }
pub fn send<T: Serialize>(&mut self, msg: T) -> Result<(), tungstenite::Error> { pub async fn send<T: Serialize>(&mut self, msg: T) -> Result<(), tungstenite::Error> {
let mut msg = serde_json::to_string(&msg).unwrap(); let mut msg = serde_json::to_string(&msg).unwrap();
msg.push('\x1E'); msg.push('\x1E');
self.sock.send(Message::Text(msg)) self.sock.send(Message::Text(msg)).await
} }
pub fn recv(&mut self) -> Result<Vec<serde_json::Value>, RecvError> { pub async fn recv(&mut self) -> Result<Vec<serde_json::Value>, RecvError> {
let msg = self.sock.read()?; let msg = self.sock.next().await
.ok_or(RecvError::EndOfStream)??;
let Message::Text(txt) = msg else { let Message::Text(txt) = msg else {
return Err(RecvError::BadMessageType); return Err(RecvError::BadMessageType);
}; };