Skip to main content

guarded_vehicle_data/
guarded_vehicle_data.rs

1//! Reads one vehicle's charge state, but only pays for it when the car is awake.
2//!
3//! `GET /api/1/vehicles/{vin}/vehicle_data` is **billed** ($0.002 per request, and a 408 from a
4//! sleeping car is billed too). `Client::send_guarded` first asks the free
5//! `GET /api/1/vehicles/{vin}` for the car's state and makes the billed call only when it
6//! says `online`. Otherwise it reports `Guarded::Skipped` and nothing is spent. The car can
7//! still fall asleep between the two calls, so this narrows the window; it does not close it.
8//!
9//! ```text
10//! TESLA_CLIENT_ID=<your app's client id> \
11//! FLEETWIRE_TOKEN_DIR=$HOME/.fleetwire \
12//! cargo run --example guarded_vehicle_data -- <VIN>
13//! ```
14//!
15//! Running it against an online car costs one billed request. `FLEETWIRE_TOKEN_DIR` is set up
16//! the same way as for `list_vehicles` (see "Quick start" in the README); `list_vehicles
17//! -- --show-vin` prints the VIN to pass here.
18
19use std::path::PathBuf;
20use std::process::ExitCode;
21use std::sync::Arc;
22
23use fleetwire::api::vehicles::{DataEndpoint, GetVehicleData};
24use fleetwire::{Billing, Client, FleetGet, Guarded, HttpRefresher, Pricing, TokenManager};
25
26fn main() -> ExitCode {
27    match run() {
28        Ok(()) => ExitCode::SUCCESS,
29        Err(e) => {
30            // Print the error's message, not its `Debug` form, and point at the README.
31            eprintln!("error: {e}");
32            // Every client error can say whether the failed call cost money.
33            if let Some(err) = e.downcast_ref::<fleetwire::Error>() {
34                eprintln!("{}", spend_after_failure(err.billing()));
35            }
36            eprintln!("See \"If it fails\" in crates/fleetwire/README.md for the usual causes.");
37            ExitCode::FAILURE
38        }
39    }
40}
41
42/// What a failed call cost, in words.
43fn spend_after_failure(billing: Billing) -> &'static str {
44    match billing {
45        Billing::Billed => "spent: this failed call was billed",
46        Billing::NotBilled => "spent: nothing, this failed call was not billed",
47        // `Unknown`: the request may have reached Tesla. Do not send it again to find out.
48        _ => "spent: unknown, the request may have reached Tesla before it failed",
49    }
50}
51
52fn run() -> Result<(), Box<dyn std::error::Error>> {
53    // Name both variables at once, so a first run does not fail twice.
54    let client_id = std::env::var("TESLA_CLIENT_ID").ok();
55    let dir = std::env::var_os("FLEETWIRE_TOKEN_DIR").map(PathBuf::from);
56    let (Some(client_id), Some(dir)) = (client_id, dir) else {
57        return Err(
58            "set TESLA_CLIENT_ID to your Tesla developer app's client id \
59                    and FLEETWIRE_TOKEN_DIR to the directory that holds tokens.json"
60                .into(),
61        );
62    };
63    let vin = std::env::args()
64        .nth(1)
65        .ok_or("pass the vehicle's VIN as the first argument")?;
66
67    let tokens = TokenManager::new(dir, Arc::new(HttpRefresher::new(client_id)));
68    let client = Client::builder(tokens).build()?;
69
70    // Ask only for charge_state: no location, so the `vehicle_location` scope is not needed.
71    let req = GetVehicleData::new(vin, vec![DataEndpoint::ChargeState])?;
72    // The request type knows its own price before anything is sent.
73    let price = match req.pricing() {
74        Pricing::Data { usd_per_request } => format!("${usd_per_request}"),
75        _ => "nothing".to_owned(),
76    };
77    let metered = client.send_guarded(&req)?;
78
79    match metered.value {
80        Guarded::Skipped { state, .. } => {
81            let state = if state.is_empty() { "unknown" } else { &state };
82            println!("car is {state}; skipped the billed call");
83            println!("spent: nothing (the state check is a free call)");
84        }
85        Guarded::Executed(data) => {
86            let battery = data
87                .charge_state
88                .as_ref()
89                .and_then(|c| c.get("battery_level"))
90                .and_then(|v| v.as_u64());
91            match battery {
92                Some(level) => println!("battery {level}%"),
93                None => println!("the response carried no charge_state.battery_level"),
94            }
95            println!("spent: one billed request ({price})");
96        }
97        _ => println!("unrecognised gate outcome"),
98    }
99
100    // The billed endpoints report their per-vehicle quota; free ones report none.
101    if let Some(rl) = metered.rate_limit {
102        println!("quota: {} of {} left", rl.remaining, rl.limit);
103    }
104    Ok(())
105}