Skip to content

About

On-demand Tesla camera stills, live clips, and dashcam/sentry clip downloads via the Owner API + WebRTC — an importable Node.js library.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

tesla-cam-client

Grab still images and short video clips from a Tesla vehicle's cameras from Node.js, over the Owner API + Hermes WebRTC path. Built for on-demand capture and polling (e.g. "grab a front-camera still every few minutes"), not continuous streaming.

Each capture reconnects from scratch — wake → signed session → Hermes → WebRTC → capture → teardown — and then fully disconnects. There is no persistent session between calls, which keeps the vehicle from being held awake and avoids burning the webcam data cap between polls.

Contents

Requirements

  • Node 18+ (uses the global fetch) and ffmpeg on PATH (used to encode frames to JPEG / MPEG-TS).
  • The vehicle must be parked and reachable on Hermes (the same conditions the Tesla app's live-camera view needs).
  • The one-time setup below: a ROLE_OWNER key registered on the vehicle, Owner API tokens, and your VIN.

Install

This package is not published to npm. Install it from a local path or a checkout:

# from a local checkout (adds a file: dependency)
npm install /path/to/tesla-cam-client

# or clone and install its own deps to run the CLI directly
git clone <repo-url> tesla-cam-client
cd tesla-cam-client && npm install

Then import it:

import { TeslaCamClient, TeslaTokenManager, TeslaCamError } from 'tesla-cam-client';

Quick start

import { TeslaCamClient } from 'tesla-cam-client';
import { writeFile } from 'node:fs/promises';

const client = new TeslaCamClient({
  accessToken: process.env.TESLA_ACCESS_TOKEN, // or getAccessToken (see Auth)
  vin: process.env.VIN,
  ownerKeyPath: './owner-key.pem',
});

const { image } = await client.getStillImage({ camera: 'FRONT' }); // Buffer (JPEG)
await writeFile('front.jpg', image);

const { clip } = await client.getClip({ camera: 'BACK', durationMs: 5000 }); // Buffer (MPEG-TS)
await writeFile('back.ts', clip);

One-time setup

Three things are needed before any call works. The first is the involved one.

1. A ROLE_OWNER key registered on the vehicle (owner-key.pem)

Signed commands are authenticated with an EC P-256 (prime256v1) key pair whose public key is registered on the car with owner privileges. Generate a key:

openssl ecparam -genkey -name prime256v1 -noout -out owner-key.pem

Then register its public key on the vehicle with owner role. This is the same key- pairing flow the Tesla app / teslamotors/vehicle-command uses (deep-link enrollment or an in-car NFC-card tap to approve the key). A key that is only ROLE_FM/driver will be rejected with insufficient-privilege on camera commands — it must be owner.

This is the hardest prerequisite and it's a vehicle-side action; the library can't do it for you. If captures fail at the session step with an auth/privilege error, the key isn't registered as owner.

2. Owner API tokens

You need a Tesla OAuth access token (short-lived, ~8h) and ideally a refresh token (~90 days) so long-running scripts can renew automatically.

Obtain them via the Owner API OAuth2 PKCE login flow (client_id=ownerapi, redirect_uri=tesla://auth/callback) — any Tesla token generator that produces an Owner API token works. Put them in .env as TESLA_ACCESS_TOKEN and TESLA_REFRESH_TOKEN (see .env.example). Note: Owner API currently only accepts login tokens, not refreshed ones — you'll need to re-login when the ~8h access token expires (see the refresh caveat below).

3. The VIN

Your vehicle's VIN string, e.g. 5YJ3E1EA4NF000000.

Auth: tokens & the Owner API refresh caveat

⚠️ Owner API currently rejects refresh-derived tokens. As of mid-2026, a token minted via the ownerapi refresh_token grant is refused by Owner API with 403 forbidden — only tokens from a fresh interactive login work (verified: a refresh done one minute after a clean login still 403s). In practice this means the ~8h access token can only be renewed by logging in again, not by refreshing.

The library is built around this: it uses your access token until it actually expires and never proactively refreshes a valid token (which would swap a working token for a rejected one and rotate away your good refresh token). When the token can't be recovered, it throws reauth_required — your cue to log in again. If Tesla ever restores refresh, the refreshToken path below starts working again with no code change.

Access tokens expire in ~8 hours. For a one-shot or short script, a static accessToken is fine. You can still pass a refreshToken (harmless, and future-proof) — the client will attempt a refresh on failure and surface reauth_required if it doesn't help:

import { TeslaCamClient } from 'tesla-cam-client';

const client = new TeslaCamClient({
  refreshToken: process.env.TESLA_REFRESH_TOKEN,
  accessToken: process.env.TESLA_ACCESS_TOKEN, // optional seed; reused until near expiry
  vin: process.env.VIN,
  ownerKeyPath: './owner-key.pem',
  // Optional: persist rotated tokens so restarts don't need a fresh login.
  onTokenRefresh: ({ accessToken, refreshToken }) =>
    writeFileSync('tokens.json', JSON.stringify({ accessToken, refreshToken })),
});

The token is used until it actually expires; refresh is only attempted on demand (after an auth failure), never proactively. If that refresh also fails (the current Owner API behavior), the call rejects with reauth_required — reauthenticate with a fresh login and update your tokens. client.refreshToken exposes the current token.

Other auth forms:

  • Static token only: pass accessToken (no refresh).
  • Bring-your-own provider: pass getAccessToken: async ({ forceRefresh }) => string if you manage tokens elsewhere (mutually exclusive with refreshToken/accessToken).
  • TeslaTokenManager is still exported if you want to share one refresher across multiple clients; pass its .getAccessToken as getAccessToken.

A resilient poller

A complete long-running example: renew tokens automatically, persist them across restarts, and back off on the data cap / an offline vehicle.

import { TeslaCamClient, TeslaCamError, TeslaCamErrorCode } from 'tesla-cam-client';
import { writeFileSync, readFileSync, existsSync } from 'node:fs';

const TOKENS = './tokens.json';
const saved = existsSync(TOKENS) ? JSON.parse(readFileSync(TOKENS, 'utf8')) : {};

const client = new TeslaCamClient({
  refreshToken: saved.refreshToken ?? process.env.TESLA_REFRESH_TOKEN,
  accessToken: saved.accessToken ?? process.env.TESLA_ACCESS_TOKEN,
  vin: process.env.VIN,
  ownerKeyPath: './owner-key.pem',
  onTokenRefresh: (t) => writeFileSync(TOKENS, JSON.stringify(t)), // survive restarts
});

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

for (;;) {
  try {
    const { image } = await client.getStillImage({ camera: 'FRONT' });
    writeFileSync(`snap-${Date.now()}.jpg`, image);
    await sleep(5 * 60_000); // every 5 minutes
  } catch (e) {
    const code = e instanceof TeslaCamError ? e.code : null;
    if (code === TeslaCamErrorCode.REAUTH_REQUIRED) {
      // A refresh won't help — a human must log in again. Alert and stop retrying.
      notifyMe('Tesla cam: reauth required — log in and update tokens');
      break;
    } else if (code === TeslaCamErrorCode.DATA_LIMIT_REACHED) {
      await sleep(30 * 60_000); // cap hit — back off hard
    } else if (code === TeslaCamErrorCode.VEHICLE_OFFLINE) {
      await sleep(10 * 60_000); // car asleep/away — try later
    } else {
      console.error('capture failed:', code ?? e.message);
      await sleep(60_000);
    }
  }
}

Camera angles

Pass camera to any capture method (case- and underscore/hyphen-insensitive, e.g. RIGHT_REPEATER == right-repeater). The available angles and exactly what each returns depend on the vehicle model and firmware. Observed on a Model 3 (mid-2026 firmware):

camera Returns
FRONT 2×2 composite grid of all cameras
GRID 2×2 composite grid
BACK single rear/backup fisheye
LEFT_REPEATER single left repeater
RIGHT_REPEATER single right repeater
LEFT_PILLAR single left B-pillar
RIGHT_PILLAR single right B-pillar

Note the mapping isn't uniform — some tokens (FRONT, GRID) return a composite, others a single feed. An unrecognized token generally falls back to a default view rather than erroring. Frame size on the test vehicle was 456×342.

Latency & the wake cycle

Every call reconnects from scratch, and the dominant cost is waking the car:

  • Cold (vehicle asleep): the first call can take 30–45s while the vehicle wakes and comes online.
  • Warm (recently active / just captured): subsequent calls are typically ~4–8s end-to-end.

getStills() exploits this: it captures N frames from one wake instead of paying the wake cost per still. Every result includes latencyMs so you can observe it.

CLI

# still image to a file (reads .env in the current dir by default)
node bin/tesla-cam-cli.mjs still --camera FRONT -o front.jpg

# several stills from one session -> still-0.jpg, still-1.jpg, ...
node bin/tesla-cam-cli.mjs stills --camera FRONT --count 5 --interval 750 -o still

# 5-second clip
node bin/tesla-cam-cli.mjs clip --camera BACK --duration 5000 -o back.ts

# continuous live view piped to a player (CLI-only convenience)
node bin/tesla-cam-cli.mjs watch | mpv -

# point at a specific .env (owner-key.pem is resolved next to it unless OWNER_KEY_PATH is set)
node bin/tesla-cam-cli.mjs still --env /etc/tesla/.env -o /tmp/front.jpg

The CLI reads VIN, TESLA_ACCESS_TOKEN, and/or TESLA_REFRESH_TOKEN from the .env (or the real environment). If TESLA_REFRESH_TOKEN is present it auto-refreshes and writes rotated tokens back to the .env. Exit codes: 2 = webcam data cap reached, 3 = reauth required (log in again), 1 = any other error, 0 = success.

API

new TeslaCamClient(options)

Provide exactly one auth source: refreshToken, accessToken, or getAccessToken.

option type notes
refreshToken string Client self-manages the token lifecycle (refresh on demand + retry).
accessToken string Static token alone (no refresh), or a seed alongside refreshToken.
onTokenRefresh (tokens) => void | Promise Called after an internal refresh with { accessToken, refreshToken, expiresAt }.
getAccessToken async ({ forceRefresh }) => string Bring-your-own provider; mutually exclusive with refreshToken/accessToken.
vin string Required.
ownerKeyPath string Path to the PEM. Provide this or ownerKeyPem.
ownerKeyPem string The PEM contents inline.
ownerApiBase string Defaults to https://owner-api.teslamotors.com.
hermesUri string Defaults to the production Hermes signaling URL.
userAgent string X-Tesla-User-Agent value.
debug boolean Log connection progress to stderr.

The constructor does no I/O — the key file and the @roamhq/wrtc native module are loaded lazily on the first capture.

await client.getStillImage({ camera?, timeoutMs? })

Returns { image: Buffer /* JPEG */, width, height, latencyMs, camera }.

await client.getStills({ camera?, count?, intervalMs?, timeoutMs? })

Capture several stills from one session (a single wake/connect) spaced roughly intervalMs apart — cheaper and gentler on the vehicle than N separate getStillImage() calls. Returns { images: [{ image: Buffer /* JPEG */, width, height, capturedAt }], count, latencyMs, camera }. count defaults to 3, intervalMs to 1000.

const { images } = await client.getStills({ camera: 'FRONT', count: 5, intervalMs: 750 });
images.forEach((s, i) => fs.writeFileSync(`front-${i}.jpg`, s.image));

await client.getClip({ camera?, durationMs?, timeoutMs? })

Returns { clip: Buffer /* MPEG-TS */, durationMs, latencyMs, camera }. durationMs defaults to 5000.

await client.openLiveStream({ camera?, onFrame, timeoutMs? })

Lower-level streaming primitive: connects once and calls onFrame(frame) for every decoded I420 frame ({ width, height, data }) until you call the returned handle.close(). You own the lifetime.

Dashcam & Sentry clips

Browse and download stored dashcam/sentry clips from the vehicle's USB drive. This rides a separate native WebRTC DataChannel (not the live-camera media path); clips are streamed as H.264 and muxed to MP4 client-side.

const dash = await client.openDashcam();          // one wake/connect for many ops
const clips = await dash.listClips();              // [{ eventPath, eventName, type, isSentry }]
const meta  = await dash.getMetadata(clips[0].eventPath);
const { video } = await dash.downloadClip({        // MP4 Buffer
  eventPath: clips[0].eventPath, camera: 'FRONT', startMs: 0, durationMs: 10000,
});
await fs.writeFile('clip.mp4', video);
await dash.close();

// one-shot convenience (each opens + closes its own session):
const clips2 = await client.listClips();
const { video: v } = await client.downloadClip({ eventPath, camera: 'BACK', durationMs: 5000 });

getMetadata returns the clip's event details, including its location and (for Sentry events) why it triggered:

field example notes
name SentryClips/2024-01-15_09-30-00 full event path
city San Francisco reverse-geocoded by the vehicle
lat / lon 37.7749 / -122.4194 estimated event location
reason sentry_aware_object_detection Sentry trigger reason (null for plain dashcam)
totalDurationMs 643577 total footage available for the event
eventEpochTimeMs / earliestClipTimeMs 1784465148000 event / earliest-clip timestamps
cameras ["front","back",...] camera angles available for this clip
thumbnail <Buffer> preview PNG streamed with the metadata (~128×83), or null
raw {...} the full decoded metadata object
  • downloadClip fetches the clip's metadata for durationMs if you omit it.
  • Cameras: FRONT, BACK, LEFT_REPEATER, RIGHT_REPEATER, LEFT_PILLAR, RIGHT_PILLAR (availability per clip is in metadata's cameras).
  • Requires the vehicle parked with a USB/flash drive present; no_flash_drive / data_limit_reached / other_phone_connected are possible dashcam statuses.
  • Set TESLA_DASHCAM_DEBUG=1 for a NAL-level trace of the data channel (protocol debugging only).

Status: verified live against a vehicle — listClips, getMetadata (including thumbnail + GPS), and downloadClip (H.264 → MP4) all confirmed end-to-end.

new TeslaTokenManager(options)

option type notes
refreshToken string Required. Owner API refresh token (~90 days).
accessToken string Optional seed access token, reused until near expiry.
onRefresh (tokens) => void | Promise Called after each refresh with { accessToken, refreshToken, expiresAt } for persistence.
refreshSkewSec number Refresh when within this many seconds of expiry. Default 300.
clientId / authBase string OAuth overrides.

.getAccessToken is pre-bound — pass it straight to TeslaCamClient's getAccessToken. .refreshToken reflects the current (possibly rotated) token.

Errors — TeslaCamError

Every failure rejects with a TeslaCamError (error.code), never a process crash. TeslaCamErrorCode exports the string constants.

code meaning
auth_failed Token rejected and no refresh is configured (static token) — supply a valid token.
reauth_required Refresh happened but Owner API still rejected the token (flagged login session / dead refresh token). A refresh can't fix it — reauthenticate interactively.
vehicle_offline Vehicle didn't come online within the retry budget.
session_failed Signed-command session couldn't be established.
hermes_connect_failed Hermes JWT fetch or WebSocket connect failed.
webrtc_timeout No usable answer / setRemoteDescription failed.
ice_failed ICE connectivity failed.
data_limit_reached The vehicle's webcam data cap was hit.
camera_unavailable The vehicle reported the requested camera unavailable.
capture_timeout The overall timeoutMs elapsed before a frame/clip was ready.

Troubleshooting

Symptom Likely cause / fix
auth_failed on every call Static token expired/invalid and no refresh configured — pass refreshToken, or supply a fresh token.
reauth_required Refresh worked but Owner API still 403s — the login session is flagged (often after heavy scripted usage) or the refresh token is dead. Log in again for a fresh session and update your tokens; a refresh alone won't recover it.
session_failed / privilege error The owner key isn't registered on the vehicle as owner (see setup step 1).
vehicle_offline after ~90s Car is asleep/out of connectivity and didn't wake in time. Retry later, or raise timeoutMs.
hermes_connect_failed Network/connectivity to Tesla's signaling, or a transient token issue.
capture_timeout but connect logs look fine ICE couldn't establish a media path, or the vehicle never sent a usable answer. Retry.
data_limit_reached You've hit the vehicle's webcam data cap. Back off (minutes+) before retrying.
failed to load @roamhq/wrtc Native module didn't install for your platform — reinstall deps on the target OS/arch.
ffmpeg errors / empty output ffmpeg not on PATH, or too old. Install a recent ffmpeg.
First call takes 40s Expected cold-wake latency — see Latency.

Notes & limitations

  • Reconnect per call by design. Each getStillImage/getClip pays the full wake+connect handshake. Use getStills() for several frames from one wake.
  • Data cap. The vehicle enforces a webcam data limit; sustained high-rate polling can trip data_limit_reached. Back off when you see it. (The exact cap/cooldown is vehicle-specific and not yet characterized here.)
  • ffmpeg required. Frames are encoded via a spawned ffmpeg; clips are MPEG-TS, stills are JPEG.
  • Camera tokens are vehicle-specific — see Camera angles.

Tests

npm test   # node --test; no live vehicle calls (network/WebSocket/wrtc are mocked)

About

On-demand Tesla camera stills, live clips, and dashcam/sentry clip downloads via the Owner API + WebRTC — an importable Node.js library.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages