use std::fmt;
use std::future::Future;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::time::Duration;
use jiff::civil::Date;
use jiff::{SignedDuration, Timestamp};
use reqwest::Method;
use secrecy::ExposeSecret as _;
use serde::Deserialize;
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use tokio::sync::Mutex;
use crate::config::Config;
use crate::de::{flexible_int, flexible_string, object_or_empty};
use crate::envelope::{self, Rejection, Reply};
use crate::model::{
Capabilities, ClimateOptions, CommandId, CommandRecords, CommandStatus, Destination, Location,
Maintenance, RawLocation, Vehicle, VehicleList, VehicleStatus, WireMaintenance, WireStatus,
};
use crate::session::{Credentials, Session};
use crate::trips::{
RawTripDayResponse, RawTripDetailResponse, Trip, TripDay, TripDetail, TripMonth, WireTripMonth,
};
use crate::{Error, Result, auth};
const CCS2_UNSUPPORTED: &str = "this vehicle uses the newer CCS2 protocol: hkconnect can read its location, \
trips and info, but its status and remote commands are not supported yet";
pub struct Client {
http: reqwest::Client,
config: Config,
credentials: Credentials,
state: Mutex<State>,
session_attempts: AtomicU64,
control_attempts: AtomicU64,
pin_rejected: AtomicBool,
}
impl fmt::Debug for Client {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Client")
.field("config", &self.config)
.field("username", &"[redacted]")
.field("has_pin", &self.credentials.has_pin())
.field("pin_rejected", &self.pin_rejected.load(Ordering::Relaxed))
.finish_non_exhaustive()
}
}
#[derive(Debug, Default)]
struct State {
session: Option<Session>,
control: Option<ControlToken>,
session_failure: Option<(u64, Error)>,
control_failure: Option<(u64, Error)>,
}
#[derive(Debug)]
struct ControlToken {
token: secrecy::SecretString,
expires_at: Timestamp,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind {
Read,
Command,
}
const MIN_POLL_INTERVAL: Duration = Duration::from_secs(1);
const MAX_WAIT: Duration = Duration::from_secs(24 * 60 * 60);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Auth {
Access,
Pin,
}
#[derive(Deserialize)]
struct ControlTokenResponse {
#[serde(rename = "controlToken", default, deserialize_with = "flexible_string")]
control_token: Option<String>,
#[serde(rename = "expiresTime", default, deserialize_with = "flexible_int")]
expires_time: Option<i64>,
}
impl Client {
pub fn new(config: Config, credentials: Credentials) -> Result<Self> {
let http = reqwest::Client::builder()
.cookie_store(true)
.gzip(true)
.connect_timeout(Duration::from_secs(10))
.timeout(Duration::from_secs(30))
.user_agent("okhttp/3.12.0")
.redirect(reqwest::redirect::Policy::none())
.build()
.map_err(Error::http)?;
Ok(Self {
http,
config,
credentials,
state: Mutex::new(State::default()),
session_attempts: AtomicU64::new(0),
control_attempts: AtomicU64::new(0),
pin_rejected: AtomicBool::new(false),
})
}
#[must_use]
pub fn with_session(mut self, session: Session) -> Self {
self.state.get_mut().session = Some(session);
self
}
pub async fn session(&self) -> Option<Session> {
self.state.lock().await.session.clone()
}
pub async fn login(&self) -> Result<Session> {
let mut state = self.state.lock().await;
let result = auth::login(&self.http, &self.config, &self.credentials).await;
self.finish_session_attempt(&mut state, result, true)
}
pub async fn vehicles(&self) -> Result<Vec<Vehicle>> {
let list: VehicleList = self.get("/api/v1/spa/vehicles").await?;
Ok(list.into_vehicles())
}
pub async fn status(&self, vehicle: &Vehicle) -> Result<VehicleStatus> {
require_legacy(vehicle)?;
let status: WireStatus = self
.get_object(&vehicle_path(vehicle, "/status/latest")?)
.await?;
Ok(status.into_status())
}
pub async fn refresh_status(&self, vehicle: &Vehicle) -> Result<VehicleStatus> {
require_legacy(vehicle)?;
let status: WireStatus = self.get_object(&vehicle_path(vehicle, "/status")?).await?;
Ok(status.into_status())
}
pub async fn location(&self, vehicle: &Vehicle) -> Result<Option<Location>> {
let raw: Value = self.get(&vehicle_path(vehicle, "/location/park")?).await?;
if !raw.is_object() {
return Ok(None);
}
let raw: RawLocation = decode(raw)?;
Ok(raw.into_location())
}
pub async fn maintenance(&self, vehicle: &Vehicle) -> Result<Maintenance> {
let raw: WireMaintenance = self
.get_object(&vehicle_path(vehicle, "/setting/alert/maintenance")?)
.await?;
Ok(raw.into_maintenance())
}
pub async fn capabilities(&self, vehicle: &Vehicle) -> Result<Capabilities> {
let profile: Value = self.get(&vehicle_path(vehicle, "/profile")?).await?;
Ok(Capabilities::from_profile(&profile))
}
pub async fn trips_in_month(
&self,
vehicle: &Vehicle,
year: i16,
month: i8,
) -> Result<TripMonth> {
if !(1..=12).contains(&month) {
return Err(Error::InvalidMonth(month));
}
let path = vehicle_path(vehicle, "/tripinfo")?;
let body = json!({ "tripPeriodType": 0, "setTripMonth": format!("{year:04}{month:02}") });
let raw: WireTripMonth = self.post_object(&path, body).await?;
Ok(raw.into_month())
}
pub async fn trips_on_day(&self, vehicle: &Vehicle, date: Date) -> Result<TripDay> {
let path = vehicle_path(vehicle, "/tripinfo")?;
let body = json!({ "tripPeriodType": 1, "setTripDay": yyyymmdd(date) });
let raw: RawTripDayResponse = self.post_object(&path, body).await?;
Ok(raw.into_day(date))
}
pub async fn trip_detail(&self, vehicle: &Vehicle, trip: &Trip) -> Result<TripDetail> {
let path = vehicle_path(vehicle, "/tripinfo/detail")?;
let r = &trip.detail_ref;
let body = json!({
"tripPeriodType": 1,
"setTripDay": r.day(),
"setTripStartTime": r.start,
"setServiceTID": r.service_tid,
"tripStartTime": r.start,
"tripEndTime": r.end,
});
let raw: RawTripDetailResponse = self.post_object(&path, body).await?;
Ok(raw.into_detail())
}
pub async fn lock(&self, vehicle: &Vehicle) -> Result<CommandId> {
self.door(vehicle, "close").await
}
pub async fn unlock(&self, vehicle: &Vehicle) -> Result<CommandId> {
self.door(vehicle, "open").await
}
async fn door(&self, vehicle: &Vehicle, action: &str) -> Result<CommandId> {
require_legacy(vehicle)?;
self.command(
&vehicle_path(vehicle, "/control/door")?,
Auth::Access,
|device_id| json!({ "action": action, "deviceId": device_id }),
)
.await
}
pub async fn start_climate(
&self,
vehicle: &Vehicle,
options: &ClimateOptions,
) -> Result<CommandId> {
require_legacy(vehicle)?;
let path = vehicle_path(vehicle, "/control/engine")?;
let body = json!({
"action": "start",
"hvacType": 1,
"options": {
"defrost": options.defrost(),
"heating1": u8::from(options.rear_defrost()),
"igniOnDuration": options.duration_minutes(),
},
"tempCode": options.temperature().to_code(),
"unit": "C",
});
self.command(&path, Auth::Access, |_| body.clone()).await
}
pub async fn stop_climate(&self, vehicle: &Vehicle) -> Result<CommandId> {
require_legacy(vehicle)?;
let path = format!(
"/api/v2/spa/vehicles/{}/control/engine",
vehicle_id(vehicle)?
);
self.command(&path, Auth::Pin, |_| json!({ "action": "stop" }))
.await
}
pub async fn hazard_lights(&self, vehicle: &Vehicle, with_horn: bool) -> Result<CommandId> {
require_legacy(vehicle)?;
let kind = if with_horn { "hornlight" } else { "light" };
let path = format!(
"/api/v2/spa/vehicles/{}/ccs2/control/{kind}",
vehicle_id(vehicle)?
);
self.command(&path, Auth::Pin, |_| json!({ "command": "on" }))
.await
}
pub async fn valet_mode(&self, vehicle: &Vehicle, on: bool) -> Result<CommandId> {
require_legacy(vehicle)?;
let path = format!(
"/api/v2/spa/vehicles/{}/control/valet",
vehicle_id(vehicle)?
);
let action = if on { "activate" } else { "deactivate" };
self.command(&path, Auth::Pin, |_| json!({ "action": action }))
.await
}
pub async fn send_destination(
&self,
vehicle: &Vehicle,
destination: &Destination,
) -> Result<CommandId> {
require_legacy(vehicle)?;
let path = format!(
"/api/v2/spa/vehicles/{}/location/routes",
vehicle_id(vehicle)?
);
let poi = json!({
"phone": "",
"waypointID": 1,
"lang": 1,
"src": "HERE",
"coord": { "lat": destination.latitude(), "lon": destination.longitude(), "alt": 0, "type": 0 },
"addr": destination.address(),
"zip": "",
"placeid": "",
"name": destination.name(),
});
self.command(
&path,
Auth::Pin,
|device_id| json!({ "deviceID": device_id, "poiInfoList": [poi.clone()] }),
)
.await
}
pub async fn command_status(
&self,
vehicle: &Vehicle,
command: &CommandId,
) -> Result<CommandStatus> {
let path = format!("/api/v1/spa/notifications/{}/records", vehicle_id(vehicle)?);
let records: CommandRecords = self.get(&path).await?;
Ok(records.status_of(command))
}
pub async fn wait_for(
&self,
vehicle: &Vehicle,
command: &CommandId,
timeout: Duration,
poll_every: Duration,
) -> Result<CommandStatus> {
poll_until(timeout, poll_every, || {
self.command_status(vehicle, command)
})
.await
}
async fn post_object<T: DeserializeOwned>(&self, path: &str, body: Value) -> Result<T> {
let raw: Value = self
.request(Method::POST, path, Auth::Access, Kind::Read, |_| {
Some(body.clone())
})
.await?
.body;
object_or_empty(raw).map_err(|e| Error::UnexpectedResponse(e.to_string()))
}
async fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
Ok(self
.request(Method::GET, path, Auth::Access, Kind::Read, |_| None)
.await?
.body)
}
async fn get_object<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
let raw: Value = self.get(path).await?;
object_or_empty(raw).map_err(|e| Error::UnexpectedResponse(e.to_string()))
}
async fn command(
&self,
path: &str,
auth: Auth,
body: impl Fn(&str) -> Value,
) -> Result<CommandId> {
let reply: Reply<Value> = self
.request(Method::POST, path, auth, Kind::Command, |device_id| {
Some(body(device_id))
})
.await?;
reply
.msg_id
.map(CommandId::new)
.ok_or_else(|| Error::UnexpectedResponse("command accepted without a msgId".into()))
}
async fn request<T: DeserializeOwned>(
&self,
method: Method,
path: &str,
auth: Auth,
kind: Kind,
body: impl Fn(&str) -> Option<Value>,
) -> Result<Reply<T>> {
if auth == Auth::Pin {
if !self.credentials.has_pin() {
return Err(Error::PinRequired);
}
if self.pin_rejected.load(Ordering::SeqCst) {
return Err(Error::InvalidPin);
}
}
let mut recovered = false;
loop {
let (session, fresh) = self.ensure_session().await.map_err(Error::before_command)?;
let mut control_used = None;
let mut sent = false;
let attempt = async {
let token = match auth {
Auth::Access => session.access_token.clone(),
Auth::Pin => {
let token = self.control_token(&session, fresh).await.map_err(|error| {
Rejection {
error: error.before_command(),
not_executed: true,
}
})?;
control_used = Some(token.clone());
token
}
};
sent = true;
self.send_once::<T>(&method, path, auth, &token, &session, &body)
.await
}
.await;
let Rejection {
error,
not_executed,
} = match attempt {
Ok(reply) => return Ok(reply),
Err(rejection) => rejection,
};
let error = match error {
Error::Authentication(message)
if kind == Kind::Command && sent && !not_executed =>
{
Error::UnexpectedResponse(format!(
"the command was answered with an error: {message}"
))
}
other => other,
};
let may_recover = !recovered
&& match kind {
Kind::Read => true,
Kind::Command => not_executed,
};
match error {
Error::Authentication(reason) if may_recover => {
tracing::debug!(%reason, "session rejected; logging in again");
let mut state = self.state.lock().await;
if state
.session
.as_ref()
.is_some_and(|s| s.access_token == session.access_token)
{
state.session = None;
state.control = None;
} else if let Some(used) = &control_used
&& state
.control
.as_ref()
.is_some_and(|c| c.token.expose_secret() == used)
{
state.control = None;
}
}
Error::InvalidDeviceId if may_recover => {
tracing::debug!("device id rejected; re-registering");
let device_id = auth::register_device(&self.http, &self.config)
.await
.map_err(Error::before_command)?;
let mut state = self.state.lock().await;
if let Some(s) = state.session.as_mut()
&& s.device_id == session.device_id
{
s.device_id = device_id;
state.control = None;
}
}
other => return Err(other),
}
recovered = true;
}
}
async fn send_once<T: DeserializeOwned>(
&self,
method: &Method,
path: &str,
auth: Auth,
token: &str,
session: &Session,
body: &impl Fn(&str) -> Option<Value>,
) -> Result<Reply<T>, Rejection> {
let mut req = self
.http
.request(method.clone(), self.config.url(path))
.header("Authorization", token)
.header("ccsp-service-id", self.config.service_id)
.header("ccsp-application-id", self.config.app_id)
.header("ccsp-device-id", &session.device_id);
if auth == Auth::Pin {
req = req.header("AuthorizationCCSP", token);
}
if let Some(b) = body(&session.device_id) {
req = req.json(&b);
}
let resp = req.send().await?;
let status = resp.status();
let bytes = resp.bytes().await?;
tracing::debug!(%method, path, %status, "api call");
envelope::parse_classified(status, &bytes)
}
async fn ensure_session(&self) -> Result<(Session, bool)> {
let seen = self.session_attempts.load(Ordering::SeqCst);
let mut state = self.state.lock().await;
if let Some(session) = &state.session
&& session.is_fresh()
{
return Ok((session.clone(), false));
}
if let Some((attempt, error)) = &state.session_failure
&& *attempt > seen
{
tracing::debug!(%error, "reusing the error of the login attempt this task waited for");
return Err(error.duplicate());
}
let mut refreshed = None;
if let Some(session) = &state.session {
match auth::refresh(&self.http, &self.config, session).await {
Err(e) if refresh_was_rejected(&e) => {
tracing::debug!(error = %e, "refresh rejected; logging in");
}
other => refreshed = Some(other),
}
}
let logged_in = refreshed.is_none();
let result = match refreshed {
Some(result) => result,
None => auth::login(&self.http, &self.config, &self.credentials).await,
};
self.finish_session_attempt(&mut state, result, logged_in)
.map(|session| (session, true))
}
fn finish_session_attempt(
&self,
state: &mut State,
result: Result<Session>,
logged_in: bool,
) -> Result<Session> {
let attempt = self.session_attempts.fetch_add(1, Ordering::SeqCst) + 1;
match result {
Ok(session) => {
state.session = Some(session.clone());
state.session_failure = None;
if logged_in {
state.control = None;
}
Ok(session)
}
Err(e) => {
state.session_failure = Some((attempt, e.duplicate()));
Err(e)
}
}
}
async fn control_token(&self, session: &Session, fresh: bool) -> Result<String> {
let pin = self.credentials.pin().ok_or(Error::PinRequired)?;
let seen = self.control_attempts.load(Ordering::SeqCst);
let mut state = self.state.lock().await;
if self.pin_rejected.load(Ordering::SeqCst) {
return Err(Error::InvalidPin);
}
if let Some(c) = &state.control
&& c.expires_at > Timestamp::now() + SignedDuration::from_secs(30)
{
return Ok(c.token.expose_secret().to_owned());
}
if let Some((attempt, error)) = &state.control_failure
&& *attempt > seen
{
return Err(error.duplicate());
}
let result = self.request_control_token(session, pin).await;
let attempt = self.control_attempts.fetch_add(1, Ordering::SeqCst) + 1;
match result {
Ok((token, expires_in)) => {
let token = format!("Bearer {token}");
state.control = Some(ControlToken {
token: token.clone().into(),
expires_at: auth::expiry_from_now(expires_in),
});
state.control_failure = None;
Ok(token)
}
Err(e) => {
let e = match e {
Error::Authentication(reason) if fresh => {
tracing::debug!(%reason, "PIN request refused right after login");
Error::InvalidPin
}
Error::Api { code, message } if auth::is_http_4xx(&code) => {
tracing::debug!(%code, %message, "PIN request refused");
Error::InvalidPin
}
other => other,
};
if matches!(e, Error::InvalidPin) {
tracing::warn!(
"the PIN was rejected; it will not be sent again by this client"
);
self.pin_rejected.store(true, Ordering::SeqCst);
}
state.control_failure = Some((attempt, e.duplicate()));
Err(e)
}
}
}
async fn request_control_token(&self, session: &Session, pin: &str) -> Result<(String, i64)> {
let resp = self
.http
.put(self.config.url("/api/v1/user/pin?token="))
.header("Authorization", &session.access_token)
.json(&json!({ "deviceId": session.device_id, "pin": pin }))
.send()
.await
.map_err(Error::http)?;
let status = resp.status();
let bytes = resp.bytes().await.map_err(Error::http)?;
tracing::debug!(method = "PUT", path = "/api/v1/user/pin", %status, "api call");
let parsed: Reply<ControlTokenResponse> = envelope::parse(status, &bytes)?;
match (parsed.body.control_token, parsed.body.expires_time) {
(Some(token), Some(expires_in)) if !token.is_empty() => Ok((token, expires_in)),
_ => Err(Error::InvalidPin),
}
}
}
fn decode<T: DeserializeOwned>(value: Value) -> Result<T> {
serde_json::from_value(value).map_err(|e| Error::UnexpectedResponse(e.to_string()))
}
fn refresh_was_rejected(e: &Error) -> bool {
match e {
Error::Authentication(_) => true,
Error::Api { code, .. } => auth::is_http_4xx(code),
_ => false,
}
}
fn is_transient(e: &Error) -> bool {
match e {
Error::Http(_) | Error::ServiceUnavailable | Error::CarTimeout => true,
Error::Api { code, .. } => code.len() == 3 && code.starts_with('5'),
_ => false,
}
}
async fn poll_until<F, Fut>(
timeout: Duration,
poll_every: Duration,
mut poll: F,
) -> Result<CommandStatus>
where
F: FnMut() -> Fut,
Fut: Future<Output = Result<CommandStatus>>,
{
let poll_every = poll_every.max(MIN_POLL_INTERVAL);
let start = tokio::time::Instant::now();
let deadline = start.checked_add(timeout.min(MAX_WAIT)).unwrap_or(start);
let mut last_status = None;
let mut last_error = None;
loop {
match poll().await {
Ok(status) if status.is_final() => return Ok(status),
Ok(status) => last_status = Some(status),
Err(e) if is_transient(&e) => {
tracing::debug!(error = %e, "command status poll failed; retrying");
last_error = Some(e);
}
Err(e) => return Err(e),
}
let next = tokio::time::Instant::now().checked_add(poll_every);
if next.is_none_or(|next| next > deadline) {
return match (last_status, last_error) {
(Some(status), _) => Ok(status),
(None, Some(e)) => Err(e),
(None, None) => unreachable!("every poll sets a status or an error"),
};
}
tokio::time::sleep(poll_every).await;
}
}
fn yyyymmdd(date: Date) -> String {
date.strftime("%Y%m%d").to_string()
}
fn vehicle_id(vehicle: &Vehicle) -> Result<&str> {
let id = vehicle.id.as_str();
let usable = !id.is_empty()
&& id != "."
&& !id.contains("..")
&& id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.'));
if usable {
Ok(id)
} else {
Err(Error::InvalidVehicleId)
}
}
fn vehicle_path(vehicle: &Vehicle, suffix: &str) -> Result<String> {
Ok(format!(
"/api/v1/spa/vehicles/{}{suffix}",
vehicle_id(vehicle)?
))
}
fn require_legacy(vehicle: &Vehicle) -> Result<()> {
if vehicle.ccs2 {
Err(Error::UnsupportedVehicle(CCS2_UNSUPPORTED))
} else {
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicU32, Ordering};
use super::*;
#[tokio::test(start_paused = true)]
async fn polling_survives_transient_errors() {
let calls = AtomicU32::new(0);
let status = poll_until(Duration::from_secs(60), Duration::from_secs(2), || async {
match calls.fetch_add(1, Ordering::SeqCst) {
0 => Err(Error::ServiceUnavailable),
1 => Ok(CommandStatus::Pending),
2 => Err(Error::CarTimeout),
_ => Ok(CommandStatus::Succeeded),
}
})
.await
.unwrap();
assert_eq!(status, CommandStatus::Succeeded);
assert_eq!(calls.load(Ordering::SeqCst), 4);
}
#[tokio::test(start_paused = true)]
async fn polling_returns_last_status_or_last_error_at_the_deadline() {
let start = tokio::time::Instant::now();
let calls = AtomicU32::new(0);
let status = poll_until(Duration::from_secs(10), Duration::from_secs(1), || async {
if calls.fetch_add(1, Ordering::SeqCst) == 0 {
Ok(CommandStatus::Pending)
} else {
Err(Error::ServiceUnavailable)
}
})
.await
.unwrap();
assert_eq!(status, CommandStatus::Pending);
assert!(start.elapsed() <= Duration::from_secs(10));
let err = poll_until(Duration::from_secs(5), Duration::from_secs(1), || async {
Err::<CommandStatus, _>(Error::ServiceUnavailable)
})
.await
.unwrap_err();
assert!(matches!(err, Error::ServiceUnavailable));
}
#[tokio::test(start_paused = true)]
async fn polling_stops_on_non_transient_errors() {
let calls = AtomicU32::new(0);
let err = poll_until(Duration::from_secs(60), Duration::from_secs(1), || async {
calls.fetch_add(1, Ordering::SeqCst);
Err::<CommandStatus, _>(Error::RateLimited)
})
.await
.unwrap_err();
assert!(matches!(err, Error::RateLimited));
assert_eq!(calls.load(Ordering::SeqCst), 1);
}
#[tokio::test(start_paused = true)]
async fn zero_interval_and_huge_timeout_are_tamed() {
let start = tokio::time::Instant::now();
let calls = AtomicU32::new(0);
poll_until(Duration::MAX, Duration::ZERO, || async {
calls.fetch_add(1, Ordering::SeqCst);
Ok(CommandStatus::Unknown)
})
.await
.unwrap();
let polls = calls.load(Ordering::SeqCst);
assert!((86_000..=86_401).contains(&polls), "{polls}");
assert!(start.elapsed() <= MAX_WAIT);
}
}