TeslaMate: Why Developers Are Dying to Self-Host Their Tesla Data
Every Tesla owner has felt that sting of helplessness. You open the official Tesla app, hoping to understand why your battery drained 15% overnight, only to find a pretty animation and zero actionable insights. Your driving data—your data—vanishes into Tesla's cloud, inaccessible for real analysis. But what if you could capture every watt, every mile, every vampire drain spike with surgical precision? What if you owned your data completely?
Enter TeslaMate, the open-source powerhouse that's making developers and data-obsessed Tesla owners abandon the stock experience. This isn't just another car app. It's a self-hosted data logger built on battle-tested technologies—Elixir, Postgres, Grafana, MQTT—that transforms your Tesla into a living data stream you control. No subscriptions. No vendor lock-in. Just pure, unfiltered telemetry flowing into dashboards that actually answer your questions.
The secret's out. Thousands of Tesla owners are already running TeslaMate in their homelabs. Here's why you should join them—and exactly how to do it.
What Is TeslaMate?
TeslaMate is a powerful, self-hosted data logger specifically designed for Tesla vehicles. Originally created by Adrian Kumpf and now actively maintained by Jakob Lichterfeld and the teslamate-org community, this open-source project has evolved into the gold standard for Tesla data enthusiasts who refuse to accept "good enough."
Built from the ground up in Elixir—a functional programming language designed for fault-tolerant, real-time systems—TeslaMate handles the complex dance of polling Tesla's API without overwhelming your car's systems. The project stores everything in PostgreSQL, ensuring your years of driving data remain queryable and portable. Visualization happens through Grafana, the industry-standard observability platform that turns raw numbers into stunning, interactive dashboards. And for the smart home crowd, TeslaMate publishes vehicle data to a local MQTT broker, enabling seamless integration with Home Assistant, Node-RED, and custom automation pipelines.
Why is TeslaMate trending now? Three forces are converging. First, Tesla's own app has stagnated—pretty but analytically shallow. Second, the self-hosting movement has exploded; developers are reclaiming their data from cloud services en masse. Third, TeslaMate's AGPL-3.0 license guarantees it stays free and open forever, attracting contributors who refuse to let commercial interests capture this critical tooling.
The project has earned OpenSSF Best Practices certification, maintains rigorous CI/CD pipelines, and publishes official Docker images with transparent versioning. This isn't hobbyist code—it's production-grade infrastructure you can trust with your vehicle's complete history.
Key Features That Make TeslaMate Irresistible
TeslaMate's feature set reads like a love letter to data-driven Tesla owners. Let's dissect what makes this tool genuinely exceptional:
High-Precision Drive Data Recording — Every trip becomes a forensic investigation. TeslaMate captures granular telemetry that the official app simply discards, enabling you to analyze efficiency patterns, acceleration behaviors, and energy consumption with millisecond-level accuracy.
Zero Vampire Drain Penalty — Here's where TeslaMate's engineering brilliance shines. The logger is obsessively optimized to let your car fall asleep as quickly as possible. Unlike naive polling solutions that keep your Tesla awake and hemorrhaging range, TeslaMate uses sophisticated state detection to minimize API calls when your vehicle doesn't need attention.
Automatic Address Lookup — Raw GPS coordinates are meaningless. TeslaMate reverse-geocodes every location automatically, so your drive logs show "Whole Foods Market, Austin" instead of "30.2672° N, 97.7431° W."
MQTT Publishing for Smart Home Integration — Your Tesla becomes a first-class citizen in your home automation ecosystem. Real-time data flows to Home Assistant for presence detection, to Node-RED for complex automations, to Telegram bots for alerts. The possibilities are limited only by your imagination.
Geo-Fencing with Custom Locations — Define "Home," "Work," "Supercharger Regular" with custom boundaries. Trigger automations when arriving or departing. Track time spent at specific locations for tax or productivity purposes.
Multi-Vehicle Support — Manage every Tesla in your household from a single instance. Compare efficiency across vehicles. Track which car needs charging first.
Charge Cost Tracking — Link energy consumption to your actual electricity rates. Generate accurate cost reports for reimbursement, tax deductions, or pure curiosity.
Historical Data Import — Already using TeslaFi or tesla-apiscraper? Migrate your historical data without losing years of accumulated insights.
18+ Specialized Dashboards — From Battery Health degradation tracking to lifetime driving maps, TeslaMate ships with analytics views that would take weeks to build manually.
Real-World Use Cases Where TeslaMate Dominates
1. The Range Anxiety Detective
Your Tesla lost 8% overnight. The app shrugs. TeslaMate reveals the truth: a software update triggered climate preconditioning at 3 AM, or a door left ajar prevented sleep. With the States dashboard, you see exactly when your car was online, asleep, or charging. The Vampire Drain dashboard quantifies losses over time, helping you identify patterns correlated with temperature, software versions, or sentry mode usage.
2. The Efficiency Optimizer
Hypermilers and data nerds unite. The Efficiency dashboard exposes your actual watt-hours per mile against EPA ratings. Compare net vs. gross consumption. Discover that your highway commute is 23% more efficient at 65 mph than 75 mph. The Drive Details view breaks down individual trips with elevation profiles, speed traces, and temperature correlations.
3. The Battery Health Monitor
Tesla won't tell you your battery's degradation curve. TeslaMate's Battery Health and Projected Range dashboards track this obsessively over months and years. Spot concerning trends before they become warranty claims. Document your battery's condition for resale value negotiations.
4. The Smart Home Architect
Using the MQTT integration, trigger your garage door when your Tesla enters the geo-fenced "Home" boundary. Automatically preheat your house when leaving work. Send Telegram alerts if charging interrupts during a scheduled session. The Timeline dashboard becomes your automation audit log, proving when your car was actually present.
5. The Fleet Manager
Running multiple Teslas for a business or family? One TeslaMate instance tracks them all. Generate per-vehicle cost reports. Identify which driver has the heaviest foot. The Mileage and Statistics dashboards aggregate or segment by vehicle at will.
Step-by-Step Installation & Setup Guide
TeslaMate's official deployment uses Docker Compose—the modern standard for self-hosted services. Here's the complete setup:
Prerequisites
- A machine running 24/7 (Raspberry Pi 4, Intel NUC, old laptop, or VPS)
- Docker and Docker Compose installed
- A Tesla account with API access
- Basic familiarity with terminal/command line
Directory Structure
Create a dedicated directory for TeslaMate:
mkdir -p ~/teslamate && cd ~/teslamate
Docker Compose Configuration
Create docker-compose.yml with the following services:
version: "3"
services:
teslamate:
image: teslamate/teslamate:latest
restart: always
environment:
- ENCRYPTION_KEY=your_secret_encryption_key # Generate with: openssl rand -base64 32
- DATABASE_USER=teslamate
- DATABASE_PASS=your_database_password
- DATABASE_NAME=teslamate
- DATABASE_HOST=database
- MQTT_HOST=mosquitto
- TZ=Your/Timezone # e.g., America/New_York
ports:
- 4000:4000
volumes:
- ./import:/opt/app/import
cap_drop:
- all
database:
image: postgres:15
restart: always
environment:
- POSTGRES_USER=teslamate
- POSTGRES_PASSWORD=your_database_password
- POSTGRES_DB=teslamate
volumes:
- teslamate-db:/var/lib/postgresql/data
grafana:
image: teslamate/grafana:latest
restart: always
environment:
- DATABASE_USER=teslamate
- DATABASE_PASS=your_database_password
- DATABASE_NAME=teslamate
- DATABASE_HOST=database
ports:
- 3000:3000
volumes:
- teslamate-grafana-data:/var/lib/grafana
mosquitto:
image: eclipse-mosquitto:2
restart: always
command: mosquitto -c /mosquitto-no-auth.conf
volumes:
- mosquitto-conf:/mosquitto/config
- mosquitto-data:/mosquitto/data
volumes:
teslamate-db:
teslamate-grafana-data:
mosquitto-conf:
mosquitto-data:
Launch Your Stack
# Pull latest images and start all services
docker-compose pull
docker-compose up -d
# Verify everything is running
docker-compose ps
Initial Configuration
- Access TeslaMate Web Interface: Navigate to
http://your-server-ip:4000 - Sign in with Tesla: Follow the OAuth flow to authorize API access
- Verify Grafana: Visit
http://your-server-ip:3000(default login: admin/admin) - Import Dashboards: TeslaMate's Grafana dashboards are pre-configured—no manual import needed
Critical Security Steps
⚠️ NEVER expose port 4000 directly to the internet without HTTPS and authentication.
Use a reverse proxy (Traefik, Nginx Proxy Manager, or Caddy) with Let's Encrypt:
# Add to your docker-compose.yml for automatic HTTPS with Traefik
traefik:
image: traefik:v2.10
restart: always
command:
- "--api.insecure=true"
- "--providers.docker=true"
- "--entrypoints.web.address=:80"
- "--entrypoints.websecure.address=:443"
- "--certificatesresolvers.letsencrypt.acme.tlschallenge=true"
- "--certificatesresolvers.letsencrypt.acme.email=your@email.com"
- "--certificatesresolvers.letsencrypt.acme.storage=/letsencrypt/acme.json"
ports:
- 80:80
- 443:443
volumes:
- /var/run/docker.sock:/var/run/docker.sock:ro
- ./letsencrypt:/letsencrypt
REAL Code Examples from TeslaMate
Let's examine actual implementation patterns using TeslaMate's architecture and integration capabilities.
Example 1: MQTT Topic Structure for Home Assistant
TeslaMate publishes to a predictable MQTT topic hierarchy. Here's how to subscribe to critical vehicle data:
import paho.mqtt.client as mqtt
import json
# TeslaMate MQTT topic structure: teslamate/cars/$car_id/$attribute
TESLAMATE_BASE = "teslamate/cars/1" # Car ID 1 for first vehicle
# Key topics you can subscribe to:
TOPICS = [
f"{TESLAMATE_BASE}/display_name", # "Model 3"
f"{TESLAMATE_BASE}/state", # "online", "asleep", "charging"
f"{TESLAMATE_BASE}/battery_level", # 78 (percentage)
f"{TESLAMATE_BASE}/charge_limit_soc", # 80 (charge limit %)
f"{TESLAMATE_BASE}/plugged_in", # true/false
f"{TESLAMATE_BASE}/latitude", # GPS coordinates
f"{TESLAMATE_BASE}/longitude",
f"{TESLAMATE_BASE}/speed", # Current speed (null when parked)
f"{TESLAMATE_BASE}/outside_temp", # Ambient temperature in °C
f"{TESLAMATE_BASE}/odometer", # Total miles/km
]
def on_connect(client, userdata, flags, rc):
"""Subscribe to all TeslaMate topics on successful connection."""
print(f"Connected with result code {rc}")
for topic in TOPICS:
client.subscribe(topic)
print(f"Subscribed to: {topic}")
def on_message(client, userdata, msg):
"""Process incoming Tesla data for Home Assistant automation triggers."""
topic = msg.topic
payload = msg.payload.decode()
# Parse numeric values where applicable
try:
value = json.loads(payload)
except json.JSONDecodeError:
value = payload
print(f"[{topic.split('/')[-1]}] {value}")
# Example automation trigger: notify when charging completes
if "battery_level" in topic and value >= 80:
print("🔋 Charge target reached! Trigger home notification.")
# Initialize MQTT client with TeslaMate broker
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
# Connect to your TeslaMate Mosquitto instance
client.connect("your-teslamate-server.local", 1883, 60)
client.loop_forever()
This Python subscriber demonstrates how TeslaMate's MQTT integration enables real-time automation. The hierarchical topic structure (teslamate/cars/$id/$metric) makes filtering trivial. Notice how the state topic lets you avoid unnecessary API polling—your automations react instantly when the car wakes or sleeps.
Example 2: PostgreSQL Query for Custom Analytics
TeslaMate stores everything in Postgres. Here's how to extract insights the dashboards don't provide:
-- Connect to TeslaMate database: psql -h localhost -U teslamate -d teslamate
-- Calculate true charging efficiency: energy added vs. wall consumption
SELECT
c.date,
c.charge_energy_added AS "kWh to Battery",
c.charge_energy_used AS "kWh from Wall",
ROUND(
(c.charge_energy_added / NULLIF(c.charge_energy_used, 0)) * 100,
2
) AS "Efficiency %",
p.name AS "Location"
FROM charges c
JOIN positions p ON c.position_id = p.id
WHERE c.charge_energy_used > 0
AND c.date >= NOW() - INTERVAL '30 days'
ORDER BY "Efficiency %" ASC
LIMIT 10;
-- Find your most efficient drives with temperature correlation
SELECT
d.start_date,
ROUND(d.distance::numeric, 2) AS "Miles",
ROUND((d.consumption / d.distance)::numeric, 2) AS "Wh/Mile",
ROUND(d.outside_temp_avg::numeric, 1) AS "Avg Temp °C",
p1.address AS "From",
p2.address AS "To"
FROM drives d
JOIN positions p1 ON d.start_position_id = p1.id
JOIN positions p2 ON d.end_position_id = p2.id
WHERE d.distance > 10 -- Filter out short trips
AND d.outside_temp_avg IS NOT NULL
ORDER BY (d.consumption / d.distance) ASC
LIMIT 10;
-- Monthly vampire drain analysis with sleep percentage
SELECT
DATE_TRUNC('month', date) AS month,
COUNT(*) FILTER (WHERE state = 'online') AS "Online Hours",
COUNT(*) FILTER (WHERE state = 'asleep') AS "Asleep Hours",
ROUND(
COUNT(*) FILTER (WHERE state = 'asleep') * 100.0 / COUNT(*),
2
) AS "Sleep %",
ROUND(AVG(ideal_battery_range_km)::numeric, 2) AS "Avg Range km"
FROM states
WHERE date >= NOW() - INTERVAL '6 months'
GROUP BY DATE_TRUNC('month', date)
ORDER BY month DESC;
These queries demonstrate TeslaMate's data richness. The efficiency calculation reveals charging losses—typically 10-15%—that Tesla never surfaces. The drive query correlates temperature with consumption, proving what every EV owner suspects: cold weather murders efficiency. The states query quantifies sleep quality, helping diagnose persistent wake issues.
Example 3: Docker Health Check and Monitoring
Production TeslaMate deployments need monitoring. Here's how to verify service health:
# Extended docker-compose.yml with health checks and resource limits
teslamate:
image: teslamate/teslamate:latest
restart: always
healthcheck:
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost:4000/health"]
interval: 30s
timeout: 10s
retries: 3
start_period: 40s
deploy:
resources:
limits:
memory: 512M
reservations:
memory: 256M
environment:
- ENCRYPTION_KEY=${TESLAMATE_ENCRYPTION_KEY}
- DATABASE_USER=${DATABASE_USER}
- DATABASE_PASS=${DATABASE_PASS}
- DATABASE_NAME=teslamate
- DATABASE_HOST=database
- MQTT_HOST=mosquitto
- TZ=${TZ:-UTC}
ports:
- 4000:4000
volumes:
- ./import:/opt/app/import
cap_drop:
- all
# Security: run as non-root
user: "1000:1000"
This production-hardened configuration adds health checks for Docker's orchestration, memory limits to prevent runaway consumption, and drops all Linux capabilities for defense in depth. The cap_drop: [all] line is critical—TeslaMate needs no special privileges, so we remove them all.
Advanced Usage & Best Practices
Backup Religiously — Your Postgres database contains irreplaceable historical data. Automate daily dumps:
#!/bin/bash
# /etc/cron.daily/teslamate-backup
BACKUP_DIR="/backups/teslamate"
mkdir -p "$BACKUP_DIR"
docker exec teslamate_database_1 pg_dump -U teslamate teslamate | \
gzip > "$BACKUP_DIR/teslamate-$(date +%Y%m%d).sql.gz"
# Keep only 30 days
find "$BACKUP_DIR" -name "*.sql.gz" -mtime +30 -delete
Optimize API Polling — TeslaMate's default settings balance data freshness with vampire drain. If you're debugging, temporarily increase polling via environment variables, but revert for daily use.
Grafana Alerting — Configure alerts for: charge interruption, unexpected wake events, geofence entry/exit during odd hours, battery level below threshold when not home.
Custom Dashboard Development — Export TeslaMate's built-in dashboards as JSON, modify in Grafana's UI, and version-control your customizations. The data model is stable and well-documented.
Security Hardening — Run TeslaMate on an isolated VLAN. Use WireGuard for remote access instead of exposing ports. Enable Postgres SSL if connecting across networks. Rotate your encryption key annually.
TeslaMate vs. Alternatives: The Brutal Truth
| Feature | TeslaMate | TeslaFi | TeslaScope | Tesla's Official App |
|---|---|---|---|---|
| Cost | Free (self-hosted) | $50-100/year | $30-70/year | Free |
| Data Ownership | ✅ You own everything | ❌ Cloud-hosted | ❌ Cloud-hosted | ❌ Tesla owns it |
| Raw Data Access | ✅ Full Postgres access | ❌ Limited export | ❌ Limited export | ❌ None |
| Custom Dashboards | ✅ Unlimited Grafana | ❌ Pre-built only | ❌ Pre-built only | ❌ None |
| MQTT/Home Assistant | ✅ Native integration | ❌ Not available | ❌ Not available | ❌ Not available |
| Vampire Drain | ✅ Optimized sleep | ⚠️ Moderate | ⚠️ Moderate | N/A |
| Historical Import | ✅ TeslaFi + scraper | ❌ N/A | ❌ N/A | ❌ N/A |
| Open Source | ✅ AGPL-3.0 | ❌ Proprietary | ❌ Proprietary | ❌ Proprietary |
| Setup Complexity | Moderate (Docker) | Zero | Zero | Zero |
The Verdict: TeslaFi and TeslaScope offer convenience at the cost of your data and ongoing fees. TeslaMate demands initial setup effort but rewards you with infinite flexibility, zero recurring costs, and true ownership. For developers, homelab enthusiasts, and privacy-conscious owners, it's not even close.
Frequently Asked Questions
Is TeslaMate safe for my Tesla account?
Yes, when using official versions from https://github.com/teslamate-org/teslamate. The project uses Tesla's official OAuth flow—your credentials never touch TeslaMate's servers. Beware of unofficial forks and fake mobile apps that have been reported for credential theft.
Does TeslaMate void my warranty?
No. TeslaMate only reads data via Tesla's public API. It doesn't modify vehicle software or hardware. It's equivalent to using the official app, just with better logging.
Can I run TeslaMate on a Raspberry Pi?
Absolutely. A Raspberry Pi 4 with 4GB RAM handles TeslaMate comfortably for single-vehicle setups. Use an SSD or high-endurance SD card—Postgres is I/O intensive.
What happens if my server goes down?
TeslaMate resumes gracefully. The Tesla API provides historical data for recent drives and charges, so brief outages cause minimal gaps. Extended outages (>24 hours) may lose granular data.
How much electricity does running TeslaMate cost?
Negligible. A Raspberry Pi 4 consumes ~5W, costing roughly $5/year in electricity. An Intel NUC might use 15W. Compare to TeslaFi's $50-100 annual subscription.
Can I migrate from TeslaFi without losing history?
Yes! TeslaMate includes a TeslaFi import feature. Your years of accumulated data transfer into Postgres, becoming queryable alongside new TeslaMate data.
Is two-factor authentication supported?
TeslaMate works with Tesla's current authentication system, including accounts with 2FA enabled. Follow the token-based setup in the official documentation if you encounter issues.
Conclusion: Your Data, Your Rules
TeslaMate represents something rare in today's tech landscape: a tool that genuinely empowers users instead of extracting value from them. By self-hosting your Tesla data, you escape subscription fatigue, preserve privacy, and unlock analytical capabilities that Tesla will never provide.
The Elixir/Postgres/Grafana/MQTT architecture isn't accidental—it's a deliberate choice by developers who understand reliability, queryability, and ecosystem integration. Whether you're optimizing efficiency, monitoring battery health, or building the ultimate smart home automation, TeslaMate delivers infrastructure-grade tooling for your personal vehicle fleet.
The setup requires more effort than signing up for TeslaFi. The payoff is immeasurably greater.
Ready to reclaim your Tesla data? Head to the official repository at https://github.com/teslamate-org/teslamate, star the project, and join thousands of owners who've already made the switch. Your future self—the one analyzing five years of pristine driving data in Grafana—will thank you.
Have questions about your TeslaMate setup? The community is active in GitHub Discussions and the project's documentation at https://docs.teslamate.org is continuously updated. Start logging today—every mile of data you miss is insight you can't recover.