guarded_vehicle_data/
guarded_vehicle_data.rs1use 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 eprintln!("error: {e}");
32 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
42fn 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 _ => "spent: unknown, the request may have reached Tesla before it failed",
49 }
50}
51
52fn run() -> Result<(), Box<dyn std::error::Error>> {
53 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 let req = GetVehicleData::new(vin, vec![DataEndpoint::ChargeState])?;
72 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 if let Some(rl) = metered.rate_limit {
102 println!("quota: {} of {} left", rl.remaining, rl.limit);
103 }
104 Ok(())
105}