TeslaMateApi is a RESTful API to get data collected by self-hosted data logger TeslaMate in JSON

TeslaMateApi

GitHub CI GitHub go.mod version Docker version Docker size Docker layers Docker pulls

TeslaMateApi is a RESTful API to get data collected by self-hosted data logger TeslaMate in JSON.

  • Written in Golang
  • Data is collected from TeslaMate Postgres database and local MQTT Broker
  • Endpoints return data in JSON format

Table of Contents

How to use

You can either use it in a Docker container or go download the code and deploy it yourself on any server.

Docker-compose

If you run the simple Docker deployment of TeslaMate, then adding this will do the trick. You'll have TeslaMateApi exposed at port 8080 locally then.

services:
  teslamateapi:
    image: tobiasehlert/teslamateapi:latest
    restart: always
    depends_on:
      - database
    environment:
      - DATABASE_USER=teslamate
      - DATABASE_PASS=secret
      - DATABASE_NAME=teslamate
      - DATABASE_HOST=database
      - MQTT_HOST=mosquitto
      - TZ=Europe/Berlin
    ports:
      - 8080:8080

If you are using TeslaMate Traefik setup in Docker with environment variables file (.env), then you can simply add this section to the services: section of the docker-compose.yml file:

services:
  teslamateapi:
    image: tobiasehlert/teslamateapi:latest
    restart: always
    depends_on:
      - database
    environment:
      - DATABASE_USER=${TM_DB_USER}
      - DATABASE_PASS=${TM_DB_PASS}
      - DATABASE_NAME=${TM_DB_NAME}
      - DATABASE_HOST=database
      - MQTT_HOST=mosquitto
      - TZ=${TM_TZ}
    labels:
      - "traefik.enable=true"
      - "traefik.port=8080"
      - "traefik.http.middlewares.redirect.redirectscheme.scheme=https"
      - "traefik.http.middlewares.teslamateapi-auth.basicauth.realm=teslamateapi"
      - "traefik.http.middlewares.teslamateapi-auth.basicauth.usersfile=/auth/.htpasswd"
      - "traefik.http.routers.teslamateapi-insecure.rule=Host(`${FQDN_TM}`)"
      - "traefik.http.routers.teslamateapi-insecure.middlewares=redirect"
      - "traefik.http.routers.teslamateapi.rule=Path(`/api`) || PathPrefix(`/api/`)"
      - "traefik.http.routers.teslamateapi.entrypoints=websecure"
      - "traefik.http.routers.teslamateapi.middlewares=teslamateapi-auth"
      - "traefik.http.routers.teslamateapi.tls.certresolver=tmhttpchallenge"

In this case, the TeslaMateApi would be accessible at teslamate.example.com/api/

Environment variables

Basically the same environment variables for the database, mqqt and timezone need to be set for TeslaMateApi as you have for TeslaMate.

Required environment variables (even if there are some default values available)

  • DATABASE_USER string (default: teslamate)
  • DATABASE_PASS string (default: secret)
  • DATABASE_NAME string (default: teslamate)
  • DATABASE_HOST string (default: database)
  • MQTT_HOST string (default: mosquitto)
  • TZ string (default: Europe/Berlin)

Optional environment variables

  • DATABASE_PORT integer (default: 5432)
  • DATABASE_TIMEOUT integer (default: 60000)
  • DATABASE_SSL boolean (default: true)
  • DEBUG_MODE boolean (default: false)
  • DISABLE_MQTT boolean (default: false)
  • MQTT_TLS boolean (default: false)
  • MQTT_PORT integer (default: 1883 / default if TLS is true: 8883)
  • MQTT_USERNAME string (default: )
  • MQTT_PASSWORD string (default: )
  • MQTT_NAMESPACE string (default: )

API documentation

More detailed documentation of every endpoint will come..

  • GET /api
  • GET /api/v1
  • GET /api/v1/cars
  • GET /api/v1/cars/:CarID
  • GET /api/v1/cars/:CarID/charges
  • GET /api/v1/cars/:CarID/charges/:ChargeID
  • GET /api/v1/cars/:CarID/drives
  • GET /api/v1/cars/:CarID/drives/:DriveID
  • GET /api/v1/cars/:CarID/status
  • GET /api/v1/cars/:CarID/updates
  • GET /api/v1/globalsettings
  • GET /api/ping

Security information

There is no possibility to get access to your Tesla account tokens by this API and we'll keep it this way!

The data that is accessible is data like the cars, charges, drives, current status, updates and global settings.

Also, apply some authentication on your webserver in front of the container, so your data is not unprotected and too exposed. In the example above, we use the same .htpasswd file as used by TeslaMate.

Credits

Owner
Tobias Lindberg
Senior Consultant | Developer | Father | Tesla enthusiast | Creator of TibiaData
Tobias Lindberg
Comments
  • Very high CPU Load after a few hours

    Very high CPU Load after a few hours

    I'm experiencing very high CPU load after using TeslaMateApi a few hours. I have two services calling the API (car/id/status endpoint), one of them every 15 seconds and the other one every 27 seconds and after a few hours (I checked after 15) CPU load of my 4 core Intel Xeon is at 99% when I restart the teslamateApi Docker container everything is back to normal but after a few hours it's up again. I checked my running processes on the debian system where docker is running on and there were multiple TeslaMateApi processes. One time I started (by accident) the container without any open ports, there was no issue, so I think the issue only occurs when my two services call the endpoint. Maybe an issue when API calls are at the same time or something like that?

  • lost mqtt connexion?

    lost mqtt connexion?

    Hi! thank you for this great addon :)

    However, I have a problem since I use it :(. It seems that the backend loose the connection with the Mosquitto server or doesn't not refresh the cached data.

    I'm polling the api/v1/cars/*/status every 1 minutes to populate a tracking database.

  • proxy POST commands to Tesla owner API

    proxy POST commands to Tesla owner API

    Have you considered/would you consider endpoints that would relay requests to the car.

    I have had a service like this on my list of ToDo's for some time. Even writing what I will generously call a proof of concept/meets my needs solution (https://github.com/wizardlyEinstein/iftttGateway/blob/master/main.go#L85 note: this code is no longer functional)

    However, with the recent changes to Tesla's Auth scheme and managing tokens, and... life... you get the point.

    Discovering this project made me realize that TeslaMate can manage the tokens...

    Does this interest you? Would you be open to Pull Requests adding operations like setting climate control, etc....

  • EndDate Can Be NULL, Causing Failed Charges Endpoint

    EndDate Can Be NULL, Causing Failed Charges Endpoint

    It's possible to have incomplete charges with missing EndDate. These aren't always valid objects either, but they shouldn't prevent the Charges endpoint from providing data. I believe this can happen when TeslaMate is offline when the charging cycle ends. I am not sure if it's also possible if the vehicle is actively charging.

    Error: sql: Scan error on column index 2, name "end_date": converting NULL to string is unsupported

    Pull Request https://github.com/tobiasehlert/teslamateapi/pull/40

  • Pass TeslaMate PUT requests to TeslaMate from TeslaMateApi

    Pass TeslaMate PUT requests to TeslaMate from TeslaMateApi

    For such cases there is PUT /api/car/1/logging/resume. It will instruct TeslaMate to resume logging and increase the polling interval for a short period.

    Pass TeslaMate PUT requests to TeslaMate from TeslaMateApi

    https://github.com/adriankumpf/teslamate/blob/00339cff452df4d56659d53cdd9e79cfe4721180/lib/teslamate_web/router.ex#L38

    Originally posted by @tobiasehlert in https://github.com/adriankumpf/teslamate/discussions/1433#discussioncomment-473385

  • Charge details giving an error

    Charge details giving an error

    API is working correctly for all endpoints except /api/v1/cars/:carid/charges/:chargeid the :carid and :chargeid I am using are both valid. The web response is ERR_EMPTY_RESPONSE The logs on the docker instance (Ubuntu server 19.10 64bit on Raspberry Pi 4) is; sql: Scan error on column index 5, name "not_enough_power_to_heat": sql/driver: couldn't convert <nil> (<nil>) into type bool

    I've checked the DB and while this column exists every row has null in this column. Note: I am in Australia and car is Model 3 and I don't believe my battery is ever heated as it's never cold enough here.

  • Empty results with /api/v1/cars/1/status

    Empty results with /api/v1/cars/1/status

    Hello,

    I have an issue with the teslamateapi. I do not get valid responses from the /api/v1/cars/1/status, however, the response of /api/v1/cars/1 is fine. How can this be?

    The logs also look fine.

    Response /api/v1/cars/1/status

    {
    	"data": {
    		"car": {
    			"car_id": 1,
    			"car_name": "MJ3"
    		},
    		"status": {
    			"display_name": "",
    			"state": "",
    			"state_since": "0001-01-01T00:53:28+00:53",
    			"odometer": 0,
    			"car_status": {
    				"healthy": false,
    				"locked": false,
    				"sentry_mode": false,
    				"windows_open": false,
    				"doors_open": false,
    				"trunk_open": false,
    				"frunk_open": false,
    				"is_user_present": false
    			},
    			"car_details": {
    				"model": "",
    				"trim_badging": ""
    			},
    			"car_exterior": {
    				"exterior_color": "",
    				"spoiler_type": "",
    				"wheel_type": ""
    			},
    			"car_geodata": {
    				"geofence": "",
    				"latitude": 0,
    				"longitude": 0
    			},
    			"car_versions": {
    				"version": "",
    				"update_available": false,
    				"update_version": ""
    			},
    			"driving_details": {
    				"shift_state": "",
    				"speed": 0,
    				"heading": 0,
    				"elevation": 0
    			},
    			"climate_details": {
    				"is_climate_on": false,
    				"inside_temp": 0,
    				"outside_temp": 0,
    				"is_preconditioning": false
    			},
    			"battery_details": {
    				"est_battery_range": 0,
    				"rated_battery_range": 0,
    				"ideal_battery_range": 0,
    				"battery_level": 0,
    				"usable_battery_level": 0
    			},
    			"charging_details": {
    				"plugged_in": false,
    				"charge_energy_added": 0,
    				"charge_limit_soc": 0,
    				"charge_port_door_open": false,
    				"charger_actual_current": 0,
    				"charger_phases": 0,
    				"charger_power": 0,
    				"charger_voltage": 0,
    				"scheduled_charging_start_time": "0001-01-01T00:53:28+00:53",
    				"time_to_full_charge": 0
    			}
    		},
    		"units": {
    			"unit_of_length": "km",
    			"unit_of_temperature": "C"
    		}
    	}
    }
    

    Response /api/v1/cars

    {
    	"data": {
    		"cars": [{
    			"car_id": 1,
    			"name": "MJ3",
    			"car_details": {
    				"eid": 19437902XXXX,
    				"vid": 18249217XXXX,
    				"vin": 5YJ3E7EA2MFXXXXX,
    				"model": "3",
    				"trim_badging": null,
    				"efficiency": 0.13
    			},
    			"car_exterior": {
    				"exterior_color": "PearlWhite",
    				"spoiler_type": "None",
    				"wheel_type": "PinwheelRefresh18"
    			},
    			"car_settings": {
    				"suspend_min": 12,
    				"suspend_after_idle_min": 15,
    				"req_not_unlocked": false,
    				"free_supercharging": false,
    				"use_streaming_api": true
    			},
    			"teslamate_details": {
    				"inserted_at": "2021-03-13T12:22:57+01:00",
    				"updated_at": "2021-03-15T09:54:24+01:00"
    			},
    			"teslamate_stats": {
    				"total_charges": X,
    				"total_drives": X,
    				"total_updates": X
    			}
    		}]
    	}
    }
    

    Logs

    teslamateapi_1  | 2021/03/16 10:54:11.855339 [info] TeslaMateAPICarsV1 /api/v1/cars/1 executed successful.
    teslamateapi_1  | [GIN] 2021/03/16 - 10:54:11 | 200 |    3.695194ms | 192.168.178.178 | GET      "/api/v1/cars/1"
    teslamateapi_1  | 2021/03/16 10:54:14.813472 [info] TeslaMateAPICarsStatusV1 /api/v1/cars/1/status executed successful.
    teslamateapi_1  | [GIN] 2021/03/16 - 10:54:14 | 200 |  775.427588ms | 192.168.178.178 | GET      "/api/v1/cars/1/status"
    

    Thank you in advance!

  • TeslaMate API commands - how to

    TeslaMate API commands - how to

    Hi there, I use the TeslaMate also in order to have some info for my NodeRed implementation of charging my Tesla M3 car. And until now, in order to start/stop charging I always use the node-red-contrib-tesla ...but this node sometime is not work. (like now for example)

    So I try to implement the Commands and I inserted this code in my docker-compose file and pull/compose again:

          - ENABLE_COMMANDS=true
          - COMMANDS_CHARGING=true
    
    

    My question now is... how can I send a charging start/stop to my Tesla car please ? Is possible to have a MQTT topic like "charging_start_stop" and change this topic from my Node-Red flow in order to start/stop charging ? Or maybe have a command MQTT topic and use it in order to send more commands type.

    I'm not a programmer so I don't know how to implement this commands. I wish to delete the node-red-contrib-tesla and use only TeslaMate in my node-red flow if possible.

    Thanks a lot in advance Denis

  • Not able to use POST commands

    Not able to use POST commands

    I am using Home Assistant to control my heating etc via rest and it was working great at the beginning.

    I am now getting a error in TeslamateApi that I cant figure out.

    2022/03/11 19:48:31.468497 [info] checkAuthToken - returning true
    2022/03/11 19:48:31.469042 [debug] validateAuthToken - header authorization bearer token valid.
    2022/03/11 19:48:31.469094 [debug] TeslaMateAPICarsCommandV1 command received: /wake_up
    [GIN] 2022/03/11 - 19:48:31 | 500 |    2.210438ms |   192.168.1.150 | POST     "/api/v1/cars/1/wake_up"
    2022/03/11 19:48:31.470614 [error] TeslaMateAPICarsCommandV1 error in http request to https://owner-api.teslamotors.com: Post "https://owner-api.teslamotors.com/api/1/vehicles/XXXXXXXXXXXXXX/wake_up": net/http: invalid header field value "Bearer \x01\nAES.GCM.V1\xb8V\xff\xafW\x95\x12\x95\xc1\xb1\xa6.\x15\xa1\xe6|\x84\x11\xf4$\x18\xedg\x98\x96\xdf\xe4l\xe8\xffE\x94嬳\xc7\xf8\x5\x95\xe9\x92\xfd\xb7I\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXx \xddm\xa5Dg\x94`7l\xf1K36\x15'Aj\xac\x17\xb1\xa7\x9aKU\x81\xc3XXXXXXXDZ:\xf1Z\xfb\xd5L\x96Gt]\x12\xb" for key Authorization
    

    I have with purpose removed some charchers in the http request.

  • Display incomplete charge data

    Display incomplete charge data

    While these are usually charges that failed, they also include charges that are in progress. The client should be able to see these Charges and decide how to proceed. These charges were, at one point, real charges with relevant data.

    Reasons for failure:

    • Charging started, TeslaMate server or Tesla API went offline
    • Charging in progress (not actually failure, just incomplete charge data)

    This will also allow the user to know about the charge's existence and query (by ID) the Charge Details. Since the database stored the many charge detail objects, the user may be able to process some additional information about the charge. Especially if the charge is in progress.

    Example:

    1. Charge is in progress.
    2. Receive basic charge data, like start date and charge ID.
    3. Query Charge Details to info like: start date, power over time, etc.

    However, even with access to this additional data that does exist, the user still will not be able to see data from when the charge went offline. Or in the case the charge is still occurring, the user can't see charge details that haven't happened yet.

    Therefore, Charge Details require an additional parameter IsChargeCompleted bool so the user knows if an object is finalized.

    The user will have to determine whether the charge is still in progress or corrupted, by seeing if there are any recent charges. If it's in progress, the user should consider refreshing that charge object in the future.

    I chose to add this as a separate object on Data so that it will not affect existing API users. This will ensure incomplete charges are not treated as completed charges.

  • sql: Scan error on column index 4, name

    sql: Scan error on column index 4, name "efficiency": converting NULL to float64 is unsupported

    When calling "http://myserver:8080/api/v1/cars" or "http://myserver:8080/api/v1/cars/1" I the following error is logged in my docker container "sql: Scan error on column index 4, name "efficiency": converting NULL to float64 is unsupported". Other endpoints work,

  • Receive a

    Receive a "200 OK" response after trying to set commands, but nothings happens.

    Tried with and without API-TOKEN, the log says:

    2022/09/16 11:01:34.539935 [info] checkAuthToken - returning true
    2022/09/16 11:01:34.539948 [debug] validateAuthToken - header authorization bearer token valid.
    
    2022/09/16 11:01:34 [Recovery] 2022/09/16 - 11:01:34 panic recovered:
    cipher: message authentication failed
    /go/src/EncryptionSupport.go:97 (0x7b8673)
    /go/src/v1_TeslaMateAPICarsCommand.go:111 (0x7bb4ab)
    /go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:173 (0x7b5d2f)
    /go/pkg/mod/github.com/gin-contrib/[email protected]/handler.go:60 (0x7b5d08)
    /go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:173 (0x75ec21)
    /go/pkg/mod/github.com/gin-gonic/[email protected]/recovery.go:101 (0x75ec0c)
    /go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:173 (0x75dd06)
    /go/pkg/mod/github.com/gin-gonic/[email protected]/logger.go:240 (0x75dce9)
    /go/pkg/mod/github.com/gin-gonic/[email protected]/context.go:173 (0x75cdd0)
    /go/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:616 (0x75ca38)
    /go/pkg/mod/github.com/gin-gonic/[email protected]/gin.go:572 (0x75c6fc)
    /usr/local/go/src/net/http/server.go:2916 (0x64afda)
    /usr/local/go/src/net/http/server.go:1966 (0x647796)
    /usr/local/go/src/runtime/asm_amd64.s:1571 (0x463760)
    
  • Feature Request: Filter drives and charges by dates

    Feature Request: Filter drives and charges by dates

    First of all thanks and nice work you have here :)

    My resquest is all about filter drives and charges by date.

    Now we can add ?page=2&show=10 to the request for pagination, but sometimes I need filter by date, with a startDate and endDate.

    For now to do that I request all drives or charges and then filter myself on frontend, but this is not very efficient, especially when database is huge.

    You can add defaults like in page and show, something like ?startDate last 5 years since now and ?endDate now.

    Thanks in advance.

  • Recommendation: Endpoint to List Available Drive/Charge IDs

    Recommendation: Endpoint to List Available Drive/Charge IDs

    This isn't an issue, but a recommendation that I want to open discussion for.

    Issue When designing a UI to hook up to this API, I find it hard to scrape for all charge and/or drive data. I may want to do this to run queries against the entire set of charge and drive data or simply to cache relevant information.

    Why It's hard to assume we have all the data since drive and charge IDs aren't always ordered one after the other. For example, if TeslaMate is down while a charge finishes, that charge will never be completed and will be considered invalid. In this case, we may have charges with ID = 1, 2, and 4, but where charge ID = 3 is an invalid charge and not relevant to the API response.

    Current Option The best existing option here is to poll the "/charges" or "/drives" endpoint and go one page at a time until an invalid response is received (and hope this is because we have exhausted the data, and not because of a TeslaMateAPI error). This leaves the client wondering just how much data there is, until the heavy lifting is finished. It also makes it hard to schedule the data fetch in the background.

    Suggestion Add a new meta endpoint to return the IDs (and potentially other basic meta) of all valid objects, like this

    Example Request: /api/v1/cars/:CarID/meta Response:

    {
        "charges": {
            "ids": [1, 2, 4, 7, 8, 9, 10, ..., 762, 764, 765]
        }, 
        "drives": { ... }
    }
    
A quick and easy way to setup a RESTful JSON API

Go-Json-Rest A quick and easy way to setup a RESTful JSON API Go-Json-Rest is a thin layer on top of net/http that helps building RESTful JSON APIs ea

Jan 3, 2023
golang crud restful api with gorm , gin and mysql DB

crud restful api with golang , gorm , gin and mysql this api does a simple CRUD operations on a single table mysql Database . this is build on top off

Feb 26, 2022
This project demonstrates a simple RESTful API built with Go and Chi.
This project demonstrates a simple RESTful API built with Go and Chi.

Go and chi RESTful API This project demonstrates a simple RESTful API built with Go and chi. This API provides the following endpoints: GET / - Verify

Dec 14, 2022
An example repo for RESTful API with swagger docs & unit testing

go REST API An example repo for RESTful API with swagger docs & unit testing Starting development server Copy .env.example to .env in the same directo

Nov 5, 2021
An restful api that uses CRUDL to support user endpoints. Stores the users in mysqlite. Creates 10 users when the program starts.

UserAPI An restful api that uses CRUDL to support user endpoints. Stores the users in mysqlite. Creates 10 users when the program starts. How to start

Nov 26, 2021
Implementing a restful-api with Golang.

Go-REST Create a restful api with Golang. The main idea behind this project was to gain some knowledge about implementing a rest-api in Golang. Setup

Aug 22, 2022
GateCracker-REST - A RESTful API example for simple lock model information application with Go
GateCracker-REST - A RESTful API example for simple lock model information application with Go

Go Lock Models REST API Example A RESTful API example for simple lock model info

Jun 11, 2022
A Golang restful API boilerplate based on Echo framework v4

A Golang restful API boilerplate based on Echo framework v4. Includes tools for module generation, db migration, authorization, authentication and more.

Nov 15, 2022
This library provides a simple framework of microservice, which includes a configurator, a logger, metrics, and of course the handler

Microservice The framework for the creation of microservices, written in Golang. (note: http microservice) Architecture microservice includes: handle

Dec 30, 2022
Simple REST API to get time from many different timezones

Timezone API Simple REST API for getting current time in different timezones. This is the first assignment from Rest-Based Microservices API Developme

Oct 31, 2021
A lightweight RESTful web framework for Go
A lightweight RESTful web framework for Go

Goweb A lightweight RESTful web framework for Go. For examples and usage, please read the Goweb API Documentation Read our Articles Who uses Goweb? "U

Jan 5, 2023
Project template for creating an RESTful webservice in Go, with relational database backend & example content.

gofound-restful Project template for creating an RESTfull webservice in Go, with relational database backend and example content. Used packages github

Dec 15, 2022
Fastrest - fast restful framework for golang.

fastrest fast restful framework for golang. Create your app directory, like mkdir myapp; cd myapp; go mod init myapp; Create initial config.toml in a

Nov 8, 2022
⚓️ Golang RESTful APIs

Golang RESTful Golang RESTful API started on January 23rd, 2022. 环境配置相关解决办法

Jan 23, 2022
Headless CMS with automatic JSON API. Featuring auto-HTTPS from Let's Encrypt, HTTP/2 Server Push, and flexible server framework written in Go.
Headless CMS with automatic JSON API. Featuring auto-HTTPS from Let's Encrypt, HTTP/2 Server Push, and flexible server framework written in Go.

Ponzu Watch the video introduction Ponzu is a powerful and efficient open-source HTTP server framework and CMS. It provides automatic, free, and secur

Dec 28, 2022
mini json response for rest api

You will avoid commands below defining every time in services. resp := Response{ Code: responseCode, Message: msg, Data: data, } http.ResponseWriter.W

Dec 7, 2021
A very basic REST service for JSON data - enough for prototyping and MVPs!

caffeine - minimum viable backend A very basic REST service for JSON data - enough for prototyping and MVPs! Features: no need to set up a database, a

Dec 24, 2022
A Go framework for building JSON web services inspired by Dropwizard

Tiger Tonic A Go framework for building JSON web services inspired by Dropwizard. If HTML is your game, this will hurt a little. Like the Go language

Dec 9, 2022
A simple blog framework built with GO. Uses HTML files and a JSON dict to give you more control over your content.

Go-Blog A simple template based blog framework. Instructions Built for GO version: 1 See the Documentation or Getting Started pages in the wiki. Notes

Sep 10, 2022