Skip to main content

list_vehicles/
list_vehicles.rs

1//! Lists the vehicles on your Tesla account.
2//!
3//! This is a free call: `GET /api/1/vehicles` is not billed, and it does not wake the car.
4//!
5//! ```text
6//! TESLA_CLIENT_ID=<your app's client id> \
7//! FLEETWIRE_TOKEN_DIR=$HOME/.fleetwire \
8//! cargo run --example list_vehicles
9//! ```
10//!
11//! `FLEETWIRE_TOKEN_DIR` must be a directory only you can access (`0700`) that holds a
12//! `tokens.json` (`0600`). See "Quick start" in the README for how to create it.
13//! The VIN is printed masked; pass `--show-vin` to print it in full.
14
15use std::path::PathBuf;
16use std::process::ExitCode;
17use std::sync::Arc;
18
19use fleetwire::api::vehicles::ListVehicles;
20use fleetwire::{Client, HttpRefresher, TokenManager};
21
22fn main() -> ExitCode {
23    match run() {
24        Ok(()) => ExitCode::SUCCESS,
25        Err(e) => {
26            // Print the error's message, not its `Debug` form, and point at the README.
27            eprintln!("error: {e}");
28            eprintln!("See \"If it fails\" in crates/fleetwire/README.md for the usual causes.");
29            ExitCode::FAILURE
30        }
31    }
32}
33
34fn run() -> Result<(), Box<dyn std::error::Error>> {
35    // Name both variables at once, so a first run does not fail twice.
36    let client_id = std::env::var("TESLA_CLIENT_ID").ok();
37    let dir = std::env::var_os("FLEETWIRE_TOKEN_DIR").map(PathBuf::from);
38    let (Some(client_id), Some(dir)) = (client_id, dir) else {
39        return Err(
40            "set TESLA_CLIENT_ID to your Tesla developer app's client id \
41                    and FLEETWIRE_TOKEN_DIR to the directory that holds tokens.json"
42                .into(),
43        );
44    };
45    let show_vin = std::env::args().any(|a| a == "--show-vin");
46
47    // The token manager refreshes the access token when it is stale and writes the rotated
48    // refresh token back to `tokens.json` before returning.
49    let tokens = TokenManager::new(dir, Arc::new(HttpRefresher::new(client_id)));
50    let client = Client::builder(tokens).build()?;
51
52    let page = client.send(&ListVehicles {
53        page: None,
54        per_page: None,
55    })?;
56
57    println!("{} vehicle(s)", page.items.len());
58    for v in &page.items {
59        let vin = v.vin.as_deref().unwrap_or("?");
60        let vin = if show_vin { vin.to_owned() } else { mask(vin) };
61        println!("- vin {vin} ยท state {}", v.state.as_deref().unwrap_or("?"));
62    }
63    Ok(())
64}
65
66/// Keeps the first three and last four characters of a VIN.
67fn mask(vin: &str) -> String {
68    let chars: Vec<char> = vin.chars().collect();
69    if chars.len() < 8 {
70        return "*".repeat(chars.len());
71    }
72    let head: String = chars[..3].iter().collect();
73    let tail: String = chars[chars.len() - 4..].iter().collect();
74    format!("{head}{}{tail}", "*".repeat(chars.len() - 7))
75}