TeslaMateApi

repository·main·Indexed 42 days ago

https://github.com/tobiasehlert/teslamateapi

A RESTful API written in Go that provides JSON access to data collected by the TeslaMate data logger. It interfaces with the TeslaMate Postgres database and MQTT broker to retrieve vehicle data, monitor battery health and charging history, and send commands to Tesla vehicles.

Tokens
10K
Snippets
18
Records
27
Agent score
51%

What's inside TeslaMateApi

  1. Enable and configure Tesla commands

    main

    Commands (e.g., waking up the car, controlling climate) are disabled by default. To use them, you must set ENABLE_COMMANDS=true and choose one of the following three methods to authorize specific commands:

    1. Command Groups: Enable specific groups of commands using boolean flags (e.g., COMMANDS_ALERT=true enables alert commands).
    2. Allowlist: Provide a path to a JSON file containing a granular list of allowed commands using COMMANDS_ALLOWLIST=/path/to/allow_list.json.
    3. Enable All: Use COMMANDS_ALL=true to enable every available command. This overrides the allowlist and group settings.

    For details on the specific fields required for each command, refer to the timdorr/tesla-api documentation.

  2. Deploy TeslaMateApi via Docker-compose

    main

    You can deploy TeslaMateApi using Docker-compose. Depending on your existing TeslaMate setup, choose one of the following configurations.

    Simple Docker Deployment

    Use this if you have a standard Docker deployment of TeslaMate. This exposes the API at port 8080 locally.

    Traefik Deployment

    If you use the TeslaMate Traefik setup with an .env file, add this service to your docker-compose.yml. This configuration includes labels for Traefik to handle routing, HTTPS redirection, and basic authentication. The API will be accessible at teslamate.example.com/api/.

    services:
      teslamateapi:
        image: tobiasehlert/teslamateapi:latest
        restart: always
        depends_on:
          - database
        environment:
          - ENCRYPTION_KEY=MySuperSecretEncryptionKey
          - DATABASE_USER=teslamate
          - DATABASE_PASS=secret
          - DATABASE_NAME=teslamate
          - DATABASE_HOST=database
          - MQTT_HOST=mosquitto
          - TZ=Europe/Berlin
        ports:
          - 8080:8080
  3. Authenticate API requests for commands and logging

    main

    To access sensitive endpoints like /api/v1/cars/:CarID/command/:Command, /api/v1/cars/:CarID/wake_up, or /api/v1/cars/:CarID/logging/:Command, you must provide an API_TOKEN (configured via environment variables, minimum 32 characters).

    Add the token to your request headers: Authorization: Bearer <token>

    If you want to use a custom header name, set API_TOKEN_HEADER (e.g., X-API-Token) and send the raw token without the Bearer prefix: X-API-Token: <token>.

    Alternative: URI Parameter

    Append the token to the URL: ?token=<token>. Warning: This is not recommended as tokens may be leaked in server logs.

  4. Configure TeslaMateApi environment variables

    main

    TeslaMateApi requires several environment variables to connect to your TeslaMate Postgres database and MQTT broker.

    Required Variables

    VariableTypeDefaultDescription
    DATABASE_USERstringteslamatePostgres user
    DATABASE_PASSstringsecretPostgres password
    DATABASE_NAMEstringteslamatePostgres database name
    DATABASE_HOSTstringdatabasePostgres host
    ENCRYPTION_KEYstringKey for encryption
    MQTT_HOSTstringmosquittoMQTT broker host
    TZstringEurope/BerlinTimezone

    Optional API & Database Variables

    • API_TOKEN: Set a custom token (minimum 32 characters) for authenticated commands.
    • API_TOKEN_HEADER: Custom header for the token (default: Authorization).
    • API_TOKEN_DISABLE: Set to true if you have external authentication (e.g., Traefik) and want to disable token requirements.
    • TESLAMATE_SSL: Boolean to enable SSL.
    • DATABASE_PORT: Integer (default 5432).
    • DEBUG_MODE: Boolean (default false).
    • DISABLE_MQTT: Boolean (default false).
    • MQTT_PORT: Integer (default 1883, or 8883 if TLS is enabled).
  5. Enable and use vehicle commands

    main

    The TeslaMate API allows sending commands to your Tesla vehicle via the TeslaMateAPICarsCommandV1 endpoint.

    Prerequisites

    1. Enable Commands: You must set the environment variable ENABLE_COMMANDS=true. If this is not set, all command requests will return a 403 Forbidden error.
    2. Encryption Key: The environment variable ENCRYPTION_KEY must be set to allow the API to decrypt the Tesla access token stored in the database.
    3. Authentication: Requests must include a valid authentication token (verified via validateAuthToken).

    Usage

    • List Allowed Commands: Perform a GET request to the endpoint to receive a JSON object containing the enabled_commands list.
    • Execute a Command: Perform a POST request to the endpoint. The URL must include the CarID and the specific Command name. The request body should contain the JSON payload required by the Tesla API for that specific command.

    Endpoint Behavior

    • Command Mapping: The API maps the :Command parameter to the Tesla API path. For example, a request to /command/wake_up is normalized to /wake_up before being sent to Tesla.
    • Security: Only commands present in the internal allowList are permitted. Attempting an unauthorized command returns a 401 Unauthorized error.
    • Tesla API Proxy: The API acts as a proxy to the Tesla Owner API. It determines the correct Tesla endpoint (Global vs. China) based on the vehicle's region and forwards the request with the decrypted Authorization: Bearer <token> header.
    // 1. Get allowed commands
    GET /cars/1/command/ HTTP
    
    // 2. Send a command (e.g., wake_up)
    POST /cars/1/command/wake_up HTTP/1.1
    Authorization: Bearer <your_api_token>
    Content-Type: application/json
    
    {
      "some_param": "value"
    }
  6. Configure TeslaMateApi logging commands via environment variables

    main

    The behavior of the Cars Logging V1 endpoint is controlled by the following environment variables:

    VariableTypeDefaultDescription
    ENABLE_COMMANDSBooleanfalseIf false, all logging command requests are rejected with 403 Forbidden.
    TESLAMATE_HOSTStringteslamateThe hostname of the TeslaMate instance.
    TESLAMATE_PORTString4000The port of the TeslaMate instance.
    TESLAMATE_SSLBooleanfalseIf true, the proxy uses https:// to communicate with TeslaMate; otherwise http://.
  7. Configure command execution via environment variables

    main

    The following environment variables control the behavior and security of the vehicle command endpoint:

    VariableDefaultDescription
    ENABLE_COMMANDSfalseIf false, all command requests are rejected with 403 Forbidden.
    ENCRYPTION_KEYRequiredUsed to decrypt the Tesla access token from the database. The API will fail with 500 Internal Server Error if this is missing.
    TESLA_API_HOSThttps://owner-api.teslamotors.comOverrides the Tesla API endpoint. If the vehicle region is detected as China, it defaults to https://owner-api.vn.cloud.tesla.cn unless overridden.
  8. Reference: TeslaMateApi available endpoints

    main

    The following RESTful endpoints are available for retrieving TeslaMate data and sending commands. Note that date parameters should use the RFC3339 UTC format (e.g., 2006-01-02T15:04:05Z).

    GET /api
    GET /api/v1
    GET /api/v1/cars
    GET /api/v1/cars/:CarID
    GET /api/v1/cars/:CarID/battery-health
    GET /api/v1/cars/:CarID/charges
      ?startDate (RFC3339)
      ?endDate (RFC3339)
      ?location
    GET /api/v1/cars/:CarID/charges/current
    GET /api/v1/cars/:CarID/charges/:ChargeID
    GET /api/v1/cars/:CarID/command
    POST /api/v1/cars/:CarID/command/:Command
    GET /api/v1/cars/:CarID/drives
      ?startDate (RFC3339)
      ?endDate (RFC3339)
      ?minDistance
      ?maxDistance
      ?location
    GET /api/v1/cars/:CarID/drives/:DriveID
    PUT /api/v1/cars/:CarID/logging/:Command
    GET /api/v1/cars/:CarID/logging
    GET /api/v1/cars/:CarID/status
    GET /api/v1/cars/:CarID/updates
    POST /api/v1/cars/:CarID/wake_up
    GET /api/v1/globalsettings
    GET /api/healthz
    GET /api/ping
    GET /api/readyz
  9. Troubleshooting: Current Charge Errors

    main

    When calling the current charge endpoint, you may encounter the following error scenarios:

    • No current charge found: Returned when no charging processes are found for the specified CarID.
    • Unable to load current charge / details: General errors related to database connectivity or data retrieval failures.
    • No active charging in progress: Returned when there are incomplete charging processes in the database, but the most recent update was more than 15 minutes ago (exceeding the maxChargeInactivityThresholdMinutes).
  10. Get car information via TeslaMateAPICarsV1

    main

    The TeslaMateAPICarsV1 endpoint retrieves information about Tesla vehicles managed by TeslaMate. It can return a list of all cars or a specific car if a CarID is provided in the URL parameters.

    If no CarID is specified, the response contains an array of all cars. If a CarID is provided, the response contains only the matching car object.

    // Note: This is a Gin-based endpoint. The specific route pattern is not explicitly defined in this file, 
    // but it utilizes a 'CarID' URL parameter.
    // Example conceptual call:
    // GET /v1/cars
    // GET /v1/cars/:CarID
  11. Use the TeslaMateApi Cars Logging V1 endpoint

    main

    The TeslaMateAPICarsLoggingV1 endpoint allows you to proxy logging commands to the underlying TeslaMate instance. It supports two primary operations:

    1. List enabled commands: A GET request returns a list of commands that are currently allowed by the allowList.
    2. Execute a command: A PUT request sends a command to a specific car. The command is determined by the :Command path parameter and the request body is passed directly to the TeslaMate API.

    Requirements

    • Environment Variable: ENABLE_COMMANDS must be set to true, otherwise the endpoint returns 403 Forbidden.
    • Authentication: A valid authentication token must be provided in the request.
    • Parameters:
      • CarID: The integer ID of the car (must not be zero).
      • Command: The specific logging command to execute (e.g., /logging/some-command).

    Behavior

    • The endpoint constructs a URL to the TeslaMate host using TESLAMATE_HOST, TESLAMATE_PORT, and TESLAMATE_SSL environment variables.
    • The command is validated against an internal allowList. If the command is not in the list, it returns 401 Unauthorized.
    • The response from the TeslaMate API is forwarded to the client, preserving the original status code.
    // 1. Get allowed commands
    GET /v1/cars/:CarID/logging HTTP/1.1
    
    // 2. Execute a command
    PUT /v1/cars/1/logging/command-name HTTP/1.1
    Authorization: Bearer <your_token>
    Content-Type: application/json
    
    {
      "param": "value"
    }
  12. Get detailed charging information for a specific car and charge

    main

    Retrieve comprehensive details about a specific charging session for a given car. The endpoint provides high-level charge data (duration, energy added, cost, location) and granular time-series data (battery levels, charger voltage/current, and temperature) for the duration of the charge.

    Endpoint Pattern: /cars/<CarID>/charges/<ChargeID>

    Response Structure: The response is wrapped in a data object containing:

    • car: Basic car information (car_id, car_name).
    • charge: Summary of the charging session including start_date, end_date, address, charge_energy_added, charge_energy_used, cost, duration_min, battery_details (start/end levels), range_ideal, range_rated, and outside_temp_avg.
    • units: The measurement units used for unit_of_length and unit_of_temperature.
    • charge.charge_details: An array of detailed snapshots containing battery_level, usable_battery_level, charger_details (current, phases, power, voltage), battery_info (heater status, range), and fast_charger_info.

    Note on Units and Timezones: Values are automatically converted based on TeslaMate settings. If unit_of_length is mi, ranges and odometer are in miles. If unit_of_temperature is F, temperatures are in Fahrenheit. Timestamps are adjusted to the user's local timezone.

    // Endpoint pattern: /cars/<CarID>/charges/<ChargeID>