use jiff::Timestamp;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::de::{
self, flexible_bool, flexible_bool_or_false, flexible_f64, flexible_int, flexible_string,
ist_timestamp, lenient, lenient_vec,
};
use crate::temperature::{self, Celsius};
use crate::{Error, Result};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Vehicle {
pub id: String,
pub vin: String,
pub name: String,
pub model: String,
pub year: Option<String>,
pub powertrain: Powertrain,
pub ccs2: bool,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Powertrain {
Petrol,
Electric,
PlugInHybrid,
Hybrid,
#[default]
Unknown,
}
impl Powertrain {
fn from_code(code: Option<&str>) -> Self {
match code {
Some("GN") => Self::Petrol,
Some("EV") => Self::Electric,
Some("PHEV" | "PE") => Self::PlugInHybrid,
Some("HV") => Self::Hybrid,
_ => Self::Unknown,
}
}
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct VehicleStatus {
pub updated_at: Option<Timestamp>,
pub engine_on: Option<bool>,
pub climate_on: Option<bool>,
pub climate_temperature: Option<Celsius>,
pub defrost_on: Option<bool>,
pub locked: Option<bool>,
pub doors_open: Option<Doors>,
pub trunk_open: Option<bool>,
pub hood_open: Option<bool>,
pub sunroof_open: Option<bool>,
pub fuel_percent: Option<f64>,
pub range: Option<Distance>,
pub low_fuel_warning: Option<bool>,
pub tyre_pressure_warning: Option<bool>,
pub washer_fluid_low: Option<bool>,
pub brake_fluid_warning: Option<bool>,
pub smart_key_battery_low: Option<bool>,
pub hazard_lights_on: Option<bool>,
pub battery_12v: Option<Battery12V>,
}
impl VehicleStatus {
#[must_use]
pub fn anything_open(&self) -> bool {
self.doors_open.as_ref().is_some_and(Doors::any)
|| self.trunk_open == Some(true)
|| self.hood_open == Some(true)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[expect(clippy::struct_excessive_bools, reason = "one flag per door")]
pub struct Doors {
pub front_left: bool,
pub front_right: bool,
pub rear_left: bool,
pub rear_right: bool,
}
impl Doors {
#[must_use]
pub fn any(&self) -> bool {
self.front_left || self.front_right || self.rear_left || self.rear_right
}
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Distance {
pub value: Option<f64>,
pub unit: DistanceUnit,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum DistanceUnit {
#[default]
Km,
Miles,
}
impl DistanceUnit {
fn from_code(code: Option<i64>) -> Self {
match code {
Some(2 | 3) => Self::Miles,
_ => Self::Km,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Battery12V {
pub percent: Option<u8>,
pub warning: Option<bool>,
}
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Location {
pub latitude: f64,
pub longitude: f64,
pub altitude_m: Option<f64>,
pub speed: Option<f64>,
pub updated_at: Option<Timestamp>,
}
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct Maintenance {
pub odometer_km: Option<f64>,
pub items: Vec<MaintenanceItem>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct MaintenanceItem {
pub name: String,
pub enabled: bool,
pub interval: ServiceInterval,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ServiceInterval {
pub km: Option<u32>,
pub months: Option<u32>,
}
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
#[non_exhaustive]
#[expect(
clippy::struct_excessive_bools,
reason = "a capability list is a set of flags"
)]
pub struct Capabilities {
pub model: Option<String>,
pub model_year: Option<String>,
pub transmission: Option<String>,
pub remote_start: bool,
pub horn_and_lights: bool,
pub lights_only: bool,
pub rear_defrost: bool,
pub steering_wheel_heat: bool,
pub seat_ventilation: bool,
pub connectivity_ends: Option<String>,
}
impl Capabilities {
pub(crate) fn from_profile(profile: &Value) -> Self {
let info = &profile["vinInfo"][0];
let flag =
|section: &str, key: &str| info[section].get(key).and_then(de::truthy).unwrap_or(false);
let text = |section: &str, key: &str| match &info[section][key] {
Value::String(s) => Some(s.clone()),
Value::Number(n) => Some(n.to_string()),
_ => None,
};
Self {
model: text("basic", "modelName"),
model_year: text("basic", "modelYear"),
transmission: text("basic", "transmission"),
remote_start: flag("option", "remoteControl"),
horn_and_lights: flag("option", "hornLightAvailable"),
lights_only: flag("option", "lightOnlyAvailable"),
rear_defrost: flag("option", "heatingRearWindow"),
steering_wheel_heat: flag("option", "heatingSteeringWheel"),
seat_ventilation: flag("option", "seatVentilation"),
connectivity_ends: text("device", "simEndDate").or_else(|| text("basic", "simEndDate")),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct CommandId(String);
impl CommandId {
pub fn new(id: impl Into<String>) -> Self {
Self(id.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for CommandId {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum CommandStatus {
Pending,
Succeeded,
Failed,
NoResponse,
Unknown,
}
impl CommandStatus {
#[must_use]
pub fn is_final(self) -> bool {
matches!(self, Self::Succeeded | Self::Failed | Self::NoResponse)
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClimateOptions {
temperature: Celsius,
duration_minutes: u8,
defrost: bool,
rear_defrost: bool,
}
impl ClimateOptions {
pub const MAX_MINUTES: u8 = 10;
#[must_use]
pub fn new(temperature: Celsius) -> Self {
Self {
temperature,
duration_minutes: Self::MAX_MINUTES,
defrost: false,
rear_defrost: false,
}
}
pub fn with_duration_minutes(mut self, minutes: u8) -> Result<Self> {
if !(1..=Self::MAX_MINUTES).contains(&minutes) {
return Err(Error::InvalidDuration(minutes));
}
self.duration_minutes = minutes;
Ok(self)
}
#[must_use]
pub fn with_defrost(mut self, on: bool) -> Self {
self.defrost = on;
self
}
#[must_use]
pub fn with_rear_defrost(mut self, on: bool) -> Self {
self.rear_defrost = on;
self
}
#[must_use]
pub fn temperature(&self) -> Celsius {
self.temperature
}
#[must_use]
pub fn duration_minutes(&self) -> u8 {
self.duration_minutes
}
#[must_use]
pub fn defrost(&self) -> bool {
self.defrost
}
#[must_use]
pub fn rear_defrost(&self) -> bool {
self.rear_defrost
}
}
impl Default for ClimateOptions {
fn default() -> Self {
Self::new(Celsius::DEFAULT)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(try_from = "DestinationFields")]
pub struct Destination {
name: String,
latitude: f64,
longitude: f64,
address: String,
}
#[derive(Deserialize)]
struct DestinationFields {
name: String,
latitude: f64,
longitude: f64,
#[serde(default)]
address: String,
}
impl TryFrom<DestinationFields> for Destination {
type Error = Error;
fn try_from(f: DestinationFields) -> Result<Self> {
Ok(Self::new(f.name, f.latitude, f.longitude)?.with_address(f.address))
}
}
impl Destination {
pub fn new(name: impl Into<String>, latitude: f64, longitude: f64) -> Result<Self> {
if !(-90.0..=90.0).contains(&latitude) || !(-180.0..=180.0).contains(&longitude) {
return Err(Error::InvalidCoordinates {
latitude,
longitude,
});
}
Ok(Self {
name: name.into(),
latitude,
longitude,
address: String::new(),
})
}
#[must_use]
pub fn with_address(mut self, address: impl Into<String>) -> Self {
self.address = address.into();
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub fn latitude(&self) -> f64 {
self.latitude
}
#[must_use]
pub fn longitude(&self) -> f64 {
self.longitude
}
#[must_use]
pub fn address(&self) -> &str {
&self.address
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct VehicleList {
#[serde(default, deserialize_with = "lenient_vec")]
vehicles: Vec<WireVehicle>,
}
impl VehicleList {
pub(crate) fn into_vehicles(self) -> Vec<Vehicle> {
self.vehicles
.into_iter()
.filter_map(WireVehicle::into_vehicle)
.collect()
}
}
#[derive(Debug, Deserialize)]
struct WireVehicle {
#[serde(rename = "vehicleId", default, deserialize_with = "flexible_string")]
id: Option<String>,
#[serde(default, deserialize_with = "flexible_string")]
vin: Option<String>,
#[serde(default, deserialize_with = "flexible_string")]
nickname: Option<String>,
#[serde(rename = "vehicleName", default, deserialize_with = "flexible_string")]
model: Option<String>,
#[serde(default, deserialize_with = "flexible_string")]
year: Option<String>,
#[serde(rename = "type", default, deserialize_with = "flexible_string")]
powertrain: Option<String>,
#[serde(
rename = "ccuCCS2ProtocolSupport",
default,
deserialize_with = "flexible_bool_or_false"
)]
ccs2: bool,
}
impl WireVehicle {
fn into_vehicle(self) -> Option<Vehicle> {
let Some(id) = self.id.filter(|id| !id.trim().is_empty()) else {
tracing::debug!("skipping a vehicle without an id");
return None;
};
let model = self.model.unwrap_or_default();
Some(Vehicle {
id,
vin: self.vin.unwrap_or_default(),
name: self
.nickname
.filter(|n| !n.trim().is_empty())
.unwrap_or_else(|| model.clone()),
model,
year: self.year,
powertrain: Powertrain::from_code(self.powertrain.as_deref()),
ccs2: self.ccs2,
})
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct WireStatus {
#[serde(default, deserialize_with = "ist_timestamp")]
time: Option<Timestamp>,
#[serde(default, deserialize_with = "flexible_bool")]
engine: Option<bool>,
#[serde(rename = "airCtrlOn", default, deserialize_with = "flexible_bool")]
air_ctrl_on: Option<bool>,
#[serde(
rename = "airTemp",
default,
deserialize_with = "temperature::from_air_temp"
)]
air_temp: Option<Celsius>,
#[serde(default, deserialize_with = "flexible_bool")]
defrost: Option<bool>,
#[serde(rename = "doorLock", default, deserialize_with = "flexible_bool")]
door_lock: Option<bool>,
#[serde(rename = "doorOpen", default, deserialize_with = "lenient")]
door_open: Option<WireDoors>,
#[serde(rename = "trunkOpen", default, deserialize_with = "flexible_bool")]
trunk_open: Option<bool>,
#[serde(rename = "hoodOpen", default, deserialize_with = "flexible_bool")]
hood_open: Option<bool>,
#[serde(rename = "sunroofOpen", default, deserialize_with = "flexible_bool")]
sunroof_open: Option<bool>,
#[serde(rename = "fuelLevel", default, deserialize_with = "flexible_f64")]
fuel_level: Option<f64>,
#[serde(default, deserialize_with = "lenient")]
dte: Option<WireDistance>,
#[serde(rename = "lowFuelLight", default, deserialize_with = "flexible_bool")]
low_fuel_light: Option<bool>,
#[serde(
rename = "tirePressureLamp",
default,
deserialize_with = "tyre_warning"
)]
tire_pressure_lamp: Option<bool>,
#[serde(
rename = "washerFluidStatus",
default,
deserialize_with = "flexible_bool"
)]
washer_fluid_status: Option<bool>,
#[serde(rename = "breakOilStatus", default, deserialize_with = "flexible_bool")]
break_oil_status: Option<bool>,
#[serde(
rename = "smartKeyBatteryWarning",
default,
deserialize_with = "flexible_bool"
)]
smart_key_battery_warning: Option<bool>,
#[serde(rename = "hazardStatus", default, deserialize_with = "flexible_bool")]
hazard_status: Option<bool>,
#[serde(default, deserialize_with = "lenient")]
battery: Option<WireBattery>,
}
impl WireStatus {
pub(crate) fn into_status(self) -> VehicleStatus {
let climate_on = self.air_ctrl_on;
VehicleStatus {
updated_at: self.time,
engine_on: self.engine,
climate_on,
climate_temperature: self.air_temp.filter(|_| climate_on == Some(true)),
defrost_on: self.defrost,
locked: self.door_lock,
doors_open: self.door_open.map(WireDoors::into_doors),
trunk_open: self.trunk_open,
hood_open: self.hood_open,
sunroof_open: self.sunroof_open,
fuel_percent: self.fuel_level,
range: self.dte.map(WireDistance::into_distance),
low_fuel_warning: self.low_fuel_light,
tyre_pressure_warning: self.tire_pressure_lamp,
washer_fluid_low: self.washer_fluid_status,
brake_fluid_warning: self.break_oil_status,
smart_key_battery_low: self.smart_key_battery_warning,
hazard_lights_on: self.hazard_status,
battery_12v: self.battery.map(WireBattery::into_battery),
}
}
}
fn tyre_warning<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
nested_flag(d, "tirePressureLampAll")
}
fn battery_warning<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
nested_flag(d, "batWarning")
}
fn nested_flag<'de, D: serde::Deserializer<'de>>(
d: D,
key: &str,
) -> Result<Option<bool>, D::Error> {
let v = Option::<Value>::deserialize(d)?;
Ok(v.as_ref().and_then(|v| v.get(key)).and_then(de::truthy))
}
#[derive(Debug, Deserialize)]
#[expect(clippy::struct_excessive_bools, reason = "one flag per door")]
struct WireDoors {
#[serde(
rename = "frontLeft",
default,
deserialize_with = "flexible_bool_or_false"
)]
front_left: bool,
#[serde(
rename = "frontRight",
default,
deserialize_with = "flexible_bool_or_false"
)]
front_right: bool,
#[serde(
rename = "backLeft",
default,
deserialize_with = "flexible_bool_or_false"
)]
back_left: bool,
#[serde(
rename = "backRight",
default,
deserialize_with = "flexible_bool_or_false"
)]
back_right: bool,
}
impl WireDoors {
fn into_doors(self) -> Doors {
Doors {
front_left: self.front_left,
front_right: self.front_right,
rear_left: self.back_left,
rear_right: self.back_right,
}
}
}
#[derive(Debug, Deserialize)]
struct WireDistance {
#[serde(default, deserialize_with = "flexible_f64")]
value: Option<f64>,
#[serde(default, deserialize_with = "flexible_int")]
unit: Option<i64>,
}
impl WireDistance {
fn into_distance(self) -> Distance {
Distance {
value: self.value,
unit: DistanceUnit::from_code(self.unit),
}
}
}
#[derive(Debug, Deserialize)]
struct WireBattery {
#[serde(rename = "batSoc", default, deserialize_with = "flexible_int")]
bat_soc: Option<u8>,
#[serde(
rename = "batSignalReferenceValue",
default,
deserialize_with = "battery_warning"
)]
warning: Option<bool>,
}
impl WireBattery {
fn into_battery(self) -> Battery12V {
Battery12V {
percent: self.bat_soc,
warning: self.warning,
}
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct RawLocation {
#[serde(default, deserialize_with = "lenient")]
coord: Option<RawCoord>,
#[serde(default, deserialize_with = "lenient")]
speed: Option<RawSpeed>,
#[serde(default, deserialize_with = "ist_timestamp")]
time: Option<Timestamp>,
}
#[derive(Debug, Deserialize)]
struct RawCoord {
#[serde(default, deserialize_with = "flexible_f64")]
lat: Option<f64>,
#[serde(default, deserialize_with = "flexible_f64")]
lon: Option<f64>,
#[serde(default, deserialize_with = "flexible_f64")]
alt: Option<f64>,
}
#[derive(Debug, Deserialize)]
struct RawSpeed {
#[serde(default, deserialize_with = "flexible_f64")]
value: Option<f64>,
}
impl RawLocation {
pub(crate) fn into_location(self) -> Option<Location> {
let coord = self.coord?;
Some(Location {
latitude: coord.lat?,
longitude: coord.lon?,
altitude_m: coord.alt,
speed: self.speed.and_then(|s| s.value),
updated_at: self.time,
})
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct WireMaintenance {
#[serde(default, deserialize_with = "flexible_f64")]
odometer: Option<f64>,
#[serde(rename = "mainList", default, deserialize_with = "lenient_vec")]
main_list: Vec<WireMaintenanceItem>,
}
impl WireMaintenance {
pub(crate) fn into_maintenance(self) -> Maintenance {
Maintenance {
odometer_km: self.odometer,
items: self
.main_list
.into_iter()
.filter_map(WireMaintenanceItem::into_item)
.collect(),
}
}
}
#[derive(Debug, Deserialize)]
struct WireMaintenanceItem {
#[serde(rename = "itemId", default, deserialize_with = "flexible_string")]
item_id: Option<String>,
#[serde(default, deserialize_with = "flexible_bool_or_false")]
enable: bool,
#[serde(default, deserialize_with = "lenient")]
items: Option<WireInterval>,
}
impl WireMaintenanceItem {
fn into_item(self) -> Option<MaintenanceItem> {
let interval = self
.items
.map_or_else(ServiceInterval::default, |i| ServiceInterval {
km: i.dist_value,
months: i.term_value,
});
Some(MaintenanceItem {
name: self.item_id?,
enabled: self.enable,
interval,
})
}
}
#[derive(Debug, Deserialize)]
struct WireInterval {
#[serde(rename = "distValue", default, deserialize_with = "flexible_int")]
dist_value: Option<u32>,
#[serde(rename = "termValue", default, deserialize_with = "flexible_int")]
term_value: Option<u32>,
}
#[derive(Debug)]
pub(crate) struct CommandRecords(pub Vec<CommandRecord>);
impl<'de> Deserialize<'de> for CommandRecords {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
lenient_vec(d).map(Self)
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct CommandRecord {
#[serde(rename = "recordId", default, deserialize_with = "flexible_string")]
record_id: Option<String>,
#[serde(default, deserialize_with = "flexible_string")]
result: Option<String>,
}
impl CommandRecords {
pub(crate) fn status_of(&self, command: &CommandId) -> CommandStatus {
self.0
.iter()
.find(|r| r.record_id.as_deref() == Some(command.as_str()))
.map_or(CommandStatus::Unknown, CommandRecord::status)
}
}
impl CommandRecord {
fn status(&self) -> CommandStatus {
match self.result.as_deref() {
None => CommandStatus::Pending,
Some("success") => CommandStatus::Succeeded,
Some("fail") => CommandStatus::Failed,
Some("non-response") => CommandStatus::NoResponse,
Some(_) => CommandStatus::Unknown,
}
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
fn records(v: Value) -> CommandRecords {
serde_json::from_value(v).unwrap()
}
#[test]
fn record_ids_compare_as_strings() {
let r = records(json!([
"junk",
{ "recordId": 42, "result": "success" },
{ "recordId": "abc", "result": null },
]));
assert_eq!(r.status_of(&CommandId::new("42")), CommandStatus::Succeeded);
assert_eq!(r.status_of(&CommandId::new("abc")), CommandStatus::Pending);
assert_eq!(r.status_of(&CommandId::new("x")), CommandStatus::Unknown);
}
#[test]
fn climate_duration_is_validated() {
let options = ClimateOptions::default();
assert_eq!(options.duration_minutes(), 10);
assert_eq!(options.temperature(), Celsius::new(22.0).unwrap());
for bad in [0, 11, 255] {
assert!(matches!(
options.with_duration_minutes(bad),
Err(Error::InvalidDuration(m)) if m == bad
));
}
assert_eq!(
options.with_duration_minutes(1).unwrap().duration_minutes(),
1
);
}
#[test]
fn destination_coordinates_are_validated() {
for (lat, lon) in [
(91.0, 0.0),
(0.0, -180.5),
(f64::NAN, 0.0),
(0.0, f64::INFINITY),
] {
assert!(
matches!(
Destination::new("x", lat, lon),
Err(Error::InvalidCoordinates { .. })
),
"{lat}, {lon}"
);
}
let d = Destination::new("x", -90.0, 180.0).unwrap();
assert_eq!(d.address(), "");
let bad = json!({ "name": "x", "latitude": 100.0, "longitude": 0.0 });
assert!(serde_json::from_value::<Destination>(bad).is_err());
}
}