pub struct Client { /* private fields */ }Expand description
A Fleet API client bound to one TokenManager.
Cheap to hold (owns a ureq::Agent, which is itself an Arc-backed
connection-pool handle) but not Clone — construct one per
long-lived caller via Client::builder.
Implementations§
Source§impl Client
impl Client
Sourcepub fn builder(tokens: TokenManager) -> ClientBuilder
pub fn builder(tokens: TokenManager) -> ClientBuilder
Starts building a client around tokens.
Examples found in repository?
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}More examples
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}Sourcepub fn send<R: FleetGet>(&self, req: &R) -> Result<R::Response, Error>
pub fn send<R: FleetGet>(&self, req: &R) -> Result<R::Response, Error>
Sends one GET request and decodes its envelope-unwrapped body as
R::Response, recovering once from a 401 and once from a 412, and —
only when the caller has opted in via
ClientBuilder::max_attempts — retrying a transient failure with
backoff.
The response type is not a free type parameter: it is
FleetGet::Response, bound by the endpoint (final fix wave, Minor
5). The earlier send<R, T> let send::<GetRegion, VehicleSummary>
compile and fail at runtime as a decode error, which is exactly what
the associated type exists to prevent.
§The two recovery paths (design §4.3/§5.1) — unconditional, always on
401 → token (design §5.1). The generation the request was sent
with is handed to TokenManager::reject_generation, which is
itself a compare-and-reject, so one call expresses both of §5.1’s
branches with no window between the comparison and the decision:
- the generation moved (a sibling request already refreshed) — the call is a no-op, and the retry picks up the sibling’s token without refreshing. Refreshing here is the bug §5.1 exists to prevent: it would discard a token that is known-good.
- the generation still matches — the token value is recorded as
rejected, so the retry’s
access_token_with_generationcall cannot satisfy itself from the cache or from the identical on-disk copy, and rotates (or adopts a sibling process’s different rotation) exactly once.
Why rejecting the value, not clearing the cache (final fix wave,
Important 1). A 401 is a server-side event: it does not move the
token’s expires_at. Merely clearing the in-memory cache therefore
recovers nothing — the retry re-reads the same file, finds
is_fresh() true, adopts it, and re-sends the byte-identical token
that was just rejected. That is a guaranteed-useless extra Fleet
request (free today, $0.002 plus a shared 60/min rate-limit slot once
A4 adds a Pricing::Data endpoint) after which the caller never
recovers without a process restart.
auth_401_forces_a_rotation_and_retries_with_a_different_token pins
the corrected behaviour on the token bytes actually put on the wire.
The forced rotation bypasses nothing: it still happens inside the
token manager’s in-process + inter-process single flight, and it is
still refused by crate::MIN_REFRESH_INTERVAL and by the
unpersisted-rotation lockout. When the interval refuses it, the
caller sees the 401, not the interval error — see the error note
below.
Its Err is deliberately ignored: it can only be the in-process
mutex deadline, which means another caller is mid-refresh — by the
time we could have taken the lock the generation would have moved and
the call would have been a no-op anyway. Treating that as fatal would
convert a benign race into a failed request.
412 → region (design §4.3). The region cache is invalidated (compare-and-clear, with the generation this request’s base URL was read at), re-resolved once, and the request retried. If re-resolution fails or is refused, the original 412 is returned rather than a pointless second request to the same host.
The 412 body is never parsed to discover the right region. The
URL in that message is the region the request was sent to, not the
one it should have gone to; GET /api/1/users/region is the only
authority (design §4.3).
Fix round 1 (Important 1): both flags now live for this method’s
entire call, shared across every opt-in retry attempt below — they
are not reset per attempt. The first cut of T8 gave every retry
attempt its own fresh 401/412 budget, which is wrong on two counts:
it lets max_attempts * RECOVERY_BUDGET extra Fleet requests happen
(real money the moment A4 adds a billed endpoint), and it is less
correct, not just more expensive — a 401 is a statement about the
token, not about which attempt hit it, so if refreshing once didn’t
fix it, refreshing again on attempt 2 won’t either (same reasoning
for 412/region). See [RECOVERY_BUDGET] for the exact resulting
bound.
§Region resolution happens before the first request
Design §4.2’s ordering is cache → resolve → bootstrap, and this
method resolves up front when the cache is empty rather than waiting
for a 412 to teach it (fix round 1 of T7, review Important 1). The
asymmetry that settles it: GET /api/1/users/region is always
unbilled (O1), so resolving eagerly costs an NA account one free
round-trip of latency, while resolving lazily costs a non-NA account
a billed failure on its first real call the moment A4 introduces
vehicle_data — that 412 lands on whatever endpoint the caller
invoked, not on the free region endpoint (design §4.3). Eager is the
cheaper failure mode.
A failed or refused pre-flight resolution is not an error: the request proceeds against the bootstrap host (design §4.2 step 3), and the 412 path below is still there to recover. This happens once per call to this method, regardless of how many opt-in retry attempts follow (fix round 1 of T8: the first cut ran this on every retry attempt, since it lived inside the per-attempt helper this method has since absorbed).
GetRegion itself is exempt. It is the resolution primitive —
dispatching it through region resolution would be circular, and would
send a redundant second copy of the very request that just answered.
A caller asking for the region still benefits from an already-warm
cache; it just never triggers a fill.
§Retry is opt-in (design §9.0) — read this before assuming it fires
At the default (max_attempts == 1, [DEFAULT_MAX_ATTEMPTS]), a
failure that reaches [crate::decode::decode] (i.e. survived any
401/412 recovery above) is returned immediately — no backoff, no
deadline check, no extra Fleet request.
default_does_not_retry_even_on_retryable_5xx pins the “no extra
request” half of that claim on a status
(Error::is_retryable says retry would be safe) deliberately
chosen to tempt a future edit into treating retryable-in-principle as
retry-now; backoff_path_is_not_entered_by_default pins the “no
extra delay” half the same way.
When max_attempts > 1, a decode failure or a transport-layer
failure (before any status even exists) is retried when
Error::is_retryable says so, up to max_attempts total decode
attempts, each pair separated by an exponential-plus-jitter backoff
sleep capped at [BACKOFF_MAX] (design §9: “exponential + jitter,
cap 30s”). Error::TransportUnknown is never retried even
though it is common and often actually safe to retry — see
Error::is_retryable’s doc for why the line is drawn at the
status/variant level rather than at “was this actually billed”.
§The chain deadline covers backoff too
ClientBuilder::retry_deadline (default 60s) bounds the elapsed
wall-clock time of the entire call — every attempt plus every sleep
between them — not just the network time of one attempt. It is
checked before each sleep, and the sleep itself is clamped to
whatever budget remains, so the chain cannot overrun the deadline by
more than the in-flight attempt’s own request_timeout. This is the
gap ClientBuilder::request_timeout alone cannot close: a
per-attempt timeout bounds one attempt, not a chain of several.
Deliberate deviation from design §9.2’s literal text. The
design says to wrap the whole chain in a single tokio::time::timeout
(“wrap the whole retry chain in tokio::time::timeout”). This method
instead tracks started.elapsed() against retry_deadline and clamps
each backoff sleep to whatever remains — the same idiom
auth::lock::retry_until_locked already uses for its own deadline.
Both close the gap §9.2 is actually about (a per-request timeout does
not bound a multi-attempt chain); the difference is what happens at
expiry. tokio::time::timeout cancels the in-flight future and
produces an opaque Elapsed with no relation to what the chain was
actually doing — here, that would discard a perfectly informative
last error (e.g. Error::Api 503) in favor of a synthetic “timed
out”, for no functional gain, since the elapsed-check achieves the
identical bound on total wall-clock time. Kept as a manual check
rather than the literal tokio::time::timeout, not because the
design was overlooked.
§Request-count bound
The bound depends on req.pricing(), and the paid one is what
costs money (A5c-2a T23 fix round 2). Read the paid row first:
req.pricing() | Fleet requests for req itself, at the default max_attempts == 1 |
|---|---|
Pricing::Data (vehicle_data, nearby_charging_sites) | exactly 1. Neither recovery arm re-sends a paid request — a 401 and a 412 are both answered responses and Error::billing calls them Billed, so a second send is a second charge |
Pricing::NotCharged (everything else) | up to max_attempts + [RECOVERY_BUDGET] = 3 (original + one 401 retry + one 412 retry) |
The + RECOVERY_BUDGET ceiling is the structural backstop for the free
row and still applies to it unchanged; see that constant’s doc.
“1” is about req, not about the wire. A paid call may still cost
unbilled requests around it: up to 2 calls to
Client::resolve_region (one pre-flight + one 412-recovery
re-resolve — the recovery still happens for paid requests, it just does
not re-fire req) and at most 1 token refresh. Those are
Pricing::NotCharged and are what lets the next call succeed.
For the free row the same two region calls and one refresh apply.
Not included in that bound (T9, design §10.1 step 1): the scope
advisory pre-check against req.required_scopes(), which runs
before region resolution and can return
Error::MissingScope having made zero Fleet requests at all. It
costs at most one more call to
TokenManager::access_token_with_generation than the loop below
already makes on its first iteration — a cache hit in every case
this method’s own tests construct, since the token was just fetched
(or refreshed) a moment earlier.
§Errors
The last attempt’s error, unchanged, once 401/412 recovery and any
opted-in retries are exhausted, the failure is not
Error::is_retryable, or the chain deadline has elapsed.
Propagates TokenManager::access_token_with_generation’s errors
(token directory/refresh failures) directly — those never reach the
retry decision at all.
One exception, and it is about money (final fix wave, Important
2): a token-layer failure on a later iteration does not overwrite
the error of the most recent actual attempt. Iteration 1 may have
received a real, billed 401 or 412; if iteration 2 then fails
inside the token layer (typically
crate::MIN_REFRESH_INTERVAL refusing the forced rotation), that
error is Error::Auth { pricing: None } — Error::billing
== NotBilled. Returning it would under-report spend and would tell
the caller “token refresh suppressed” for what was really an
authentication rejection by the server. The retained prior error is
returned instead, pricing and message intact;
a_suppressed_recovery_refresh_still_reports_the_401s_billing pins
it. The token-layer error is only surfaced when there is no prior
response error — i.e. on the first iteration.
Examples found in repository?
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}Sourcepub fn send_metered<R: FleetGet>(
&self,
req: &R,
) -> Result<Metered<R::Response>, Error>
pub fn send_metered<R: FleetGet>( &self, req: &R, ) -> Result<Metered<R::Response>, Error>
Same as Client::send, but also returns the request quota the
response reported (measured 2026-08-03: paid device_data calls
carry ratelimit-device-data-per-vehicle-{limit,remaining,reset}
headers; unmetered endpoints send none of them).
Success path only. An error response can carry these headers
too (the 408s measured 2026-08-03 did), but surfacing that is a
separate concern from this method — Error does not carry a
RateLimit field, so a failed call never reaches here at all.
See RateLimit and Metered for why there is no
Client::last_rate_limit() global slot instead: a single slot would be
overwritten by whichever response landed last, so the value must ride
on the exact response that produced it.
The quota’s scope is unmeasured — open item O16 in this
crate’s module doc. The header is named per-vehicle, but the O1
evidence matrix’s own text reads account-shared, and this subproject’s
measurement (one account, one vehicle) cannot tell the two apart. An
earlier draft of this paragraph asserted per-vehicle here while the
module doc asserted account-shared; neither claim is measured, and the
reason for per-response delivery above does not depend on which is
true.
§Errors
Same as Client::send.
Sourcepub fn send_raw<R: FleetGet>(&self, req: &R) -> Result<Metered<Value>, Error>
pub fn send_raw<R: FleetGet>(&self, req: &R) -> Result<Metered<Value>, Error>
Same request as Client::send_metered, but hands back the response
body verbatim as one serde_json::Value instead of this
endpoint’s model type.
§Why this exists — the one thing typed responses cannot do
This crate’s model types are deliberately tolerant: every one carries a
#[serde(flatten)] extra map, so a field Tesla adds is absorbed
silently and a consumer never breaks (crate::model’s module doc).
That tolerance is also a blindfold — from a decoded
crate::model::VehicleSummary there is no way to see that a field
appeared, only that something ended up in extra. For the six
endpoints whose WireResponse is a model type rather than a
serde_json::Value, the raw bytes are gone by the time send returns,
and FleetGet is sealed, so no downstream crate can define a
Value-shaped request to get them back either.
This method is therefore the only way to observe Fleet API schema
drift without shipping a new version of this library. It is what the
fleetwire-capture operations tool is built on.
§It returns unscrubbed data
The value is the response exactly as Tesla sent it: VIN, GPS coordinates, odometer, addresses, charge history — whatever the endpoint carries, with none of the redaction the error paths apply.
- Do not
Debug-print, log, or serialise it anywhere it could be retained. The model types incrate::modeldeliberately implement noDebugfor this reason (REQ-18); a bareValuehas one, and that is a footgun this doc cannot remove. - Treat the value as PII for its whole lifetime, and scrub before it reaches disk, a log, or a repository.
§It does not validate the body against the endpoint
Client::send proves the body still fits this endpoint’s type;
failing that check is the drift signal. send_raw proves only that
the body is syntactically valid JSON and that the response was not an
error. Any schema judgement is the caller’s.
§What is identical to Client::send — no guard is bypassed
Same code path (send_inner), so all of it still applies: the scope
pre-check; region resolution and its host validation; the token
injection, expiry refresh and generation handling; the transport’s
refusal to follow redirects (a 3xx is Error::Api, never a
followed hop); the body-size ceiling and the content-type check; 4xx
and 5xx becoming Error rather than being handed back as data; and
the 401/412 recovery budget.
Including the retry policy. max_attempts defaults to 1, which
is “no retry” — there is no separate retry path here.
That default is not what stops a paid request from being billed
twice, and two earlier drafts of this paragraph said it was. The
first blamed a 408; the second moved the same claim onto a retryable
5xx. Both are wrong, and the code says so in one place:
Error::is_retryable admits exactly TransportNotSent and
500 | 502 | 503 | 504, and on a Pricing::Data endpoint
Error::billing judges every one of those
crate::Billing::NotBilled (error.rs’s Api arm: status >= 500
→ NotBilled). A 408 is billed but is not retryable at all, so
raising max_attempts could never duplicate one either. Measured
(RECOVERY_BUDGET’s doc, PROBE-E — paid vehicle_data, always 503,
.max_attempts(3)): 3 requests, billing == NotBilled.
What opting in actually spends on a paid endpoint is therefore
unbilled requests plus shared device_data quota — against a meter
Tesla does not contractually bind to design §9.2’s model. That residual
uncertainty, not a known billed duplicate, is why the default stays 1
and why fleetwire-capture never opts in.
The path that really could send a billed request twice under the
default is the 401/412 recovery budget mentioned above (a 401 and a 412
are Billed); it is pricing-aware and re-fires nothing paid.
The envelope is not unwrapped: the value still has its
{"response": …} wrapper, and any sibling of response — pagination,
the measured count (open item O13) — is present. The typed path drops
unmodelled siblings, which is exactly what a drift detector must not do.
§Errors
Same as Client::send, plus Error::Decode when the body is not
valid JSON at all.
Sourcepub fn send_guarded<R: VehicleEndpoint>(
&self,
req: &R,
) -> Result<Metered<Guarded<R::Response>>, Error>
pub fn send_guarded<R: VehicleEndpoint>( &self, req: &R, ) -> Result<Metered<Guarded<R::Response>>, Error>
Checks req’s vehicle’s connectivity state with a free probe
before making req’s (possibly billed) call, and skips the call
entirely when the vehicle is not online.
Measured 2026-08-03 against the live API: GET /api/1/vehicles/{vin}
(the probe this method issues) returns no ratelimit-* headers, so
it does not draw on the metered device_data quota. A sleeping
vehicle, by contrast, answers vehicle_data with HTTP 408 while
still consuming both the $0.002 charge and one of the 60
per-vehicle quota slots (watched remaining step 59 → 58 → 57 across
three consecutive calls). This method spends the free probe to avoid
paying for that 408 when it can.
Not a strict win — and on an unpaid endpoint, a pure loss.
R: VehicleEndpoint admits every one of this crate’s 11 vehicle
endpoints, 9 of which are Pricing::NotCharged. Gating one of those
nine (e.g. send_guarded(&GetVehicle::new(vin)?)) buys nothing — the
probe and the gated call are both free, so the method just issues the
same request twice — and even on the two billed endpoints
(crate::api::vehicles::GetVehicleData,
crate::api::vehicles::GetNearbyChargingSites), whether the gate
saves money overall depends entirely on how often a caller’s vehicle
is actually asleep, which only the caller knows. That is why this
crate does not gate every call automatically, why this method is not
the default way to reach a VehicleEndpoint, and why the gate is
worth reaching for only on those two billed endpoints.
Request bound: double Client::send’s. Client::send
documents its own worst case as max_attempts + RECOVERY_BUDGET
Fleet requests. This method makes up to two such calls — the free
probe, then (if online) req’s own call — so its worst case is
twice that bound: 2 * (max_attempts + RECOVERY_BUDGET), which is
6 requests at the default (max_attempts == 1). Reassuringly, at
most one of those two halves is ever billed (the probe is unmetered
and, on the O1 evidence, unbilled — O17), so the gate can never cost
more money than calling Client::send directly would — only more
requests.
TOCTOU: reduces cost, does not eliminate it. The vehicle can fall asleep in the gap between the probe response and the paid call this method then makes — that race is not closed, and the 408 it produces is, per the measurement above, still billed. This gate removes the common case (already asleep when the caller asks), not every case.
Fail-closed. If the probe itself errors — network failure,
401, 5xx, anything — this method returns that error and does not
fall through to the paid call. The gate exists to answer “should I
spend money”; proceeding anyway when it cannot answer would cost more
than not having the gate at all (a failed free probe and a paid
call, instead of just the paid call). A caller who wants to force the
paid call regardless can call Client::send directly — that is
exactly why the two methods are kept separate rather than folding a
“force” flag into one.
state is deliberately a plain String, not an enum: the only bit
this gate needs is “is it online”. If Tesla ever renamed that
string, an enum would either fail to parse the new value or collapse
it to some Unknown variant, whereas a bare string passes whatever
Tesla actually sent straight through to the caller. A rename would
make every call here fall into Guarded::Skipped — which is the
safe direction, since it drives the gate’s cost to zero rather
than to a false “go ahead and spend” — and the state string carried
on Skipped is exactly the diagnostic a caller would need to notice
and report the rename.
Returns a Metered wrapper so the gate and the quota observation
compose. Before A5 this method used Client::send twice and dropped
the ratelimit-* headers entirely, which made the two mutually
exclusive: the gate exists for the two billed endpoints, and those are
the only endpoints that emit those headers. Saving money meant losing
the quota view. Metered<Guarded<T>> adds no new type — the two
orthogonal axes (was the paid call made / what quota did we observe)
compose out of the types that already existed.
§Errors
The probe’s error (Client::send on a GetVehicle built from
req.vin()), unchanged, if the probe fails. Otherwise, req’s own
error if the paid call is made and fails.
Examples found in repository?
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}