Scheduling a Tesla Powerwall's backup reserve when the app won't
Motivation
I’ve paired a Tesla Powerwall 3 with the Octopus Intelligent Go tariff - along with solar and a heatpump. The cheap window is 23:30 to 05:30 so you fill up the battery with cheap juice and use it from 05:30 to 23:30 when the unit rate is 6x more expensive.
The Tesla app used to do this. I mean it’s probably the easiest task in software - start drawing from the grid at 23:30 and stop drawing at 05:30. But parts of the Tesla software are just dogshit to put it gently. So I retire Fido and put my own scheduler in place.
Three doors
In 2026, I think there’s really only one way to control a Powerwall - the Fleet API. You create a developer application, register it, and authorise it once. Each one has a gatekeeper.
The Fleet API
Creating the application
developer.tesla.com - sign in, add a payment method (personal use costs nothing), create an application. The form wants an Allowed Origin URL and a Redirect URI. The validator is picky. https://localhost/ fails for needing a path. https://localhost/callback fails for needing a valid host. I ended up using a domain I own, which is fine: the redirect target does not need to serve anything. After you approve access in the browser, the page lands on https://yourdomain/callback?code=..., shows a 404, and you copy the address bar.
The application gives a client ID and client secret. These identify the application, not you. A bearer token identifies you authorising the application. The client secret alone cannot touch anyone’s Powerwall - which is the entire point of OAuth.
The one-character bug
Use your favourite LLM to write the tiresome OAuth flow: PKCE, a code verifier, a redirect, a token exchange. Be sure to point your LLM at the latest Tesla docs - my GLM clanker used /oauth/v3/authorize from its training data but as of the time of writing the correct root URL is /oauth2/v3/.
The login form appeared and will try to callback to the callback endpoint I specified when registering my app. That can 404 - you just want the callback URI in the browser address bar.
Registering the application - and the key on the domain
With a token in hand I called the Fleet API:
412 {"error":"Account <client_id> must be registered in the current region https://fleet-api.prd.eu.vn.cloud.tesla.com, please see .../partner-endpoints#register"}
The registration call has two requirements that are not obvious from the error.
It needs a partner token, not a user token. That is a client_credentials grant - no browser, just the client ID and secret.
It needs an EC public key on your domain. Tesla downloads https://<your-domain>/.well-known/appspecific/com.tesla.3p.public-key.pem and demands a direct 200. The key must be EC prime256v1 - not RSA, which is what I generated first out of habit.
The first domain I tried forwards everything to GitHub Pages with a 301. Tesla does not follow it. A redirect is not a 200. So I used a second domain on a plain nginx box and dropped the file in the web root.
Registration succeeded. The 412 was gone.
Reading and writing
The reserve lives on site_info, not in the products list:
GET /api/1/energy_sites/{site_id}/site_info
-> {"response":{"site_name":"My Home","backup_reserve_percent":0, ...}}
Writing it is one call:
POST /api/1/energy_sites/{site_id}/backup
{"backup_reserve_percent": 20}
-> {"response":{"Message":"Backup reserve updated","Code":200}}
The Tesla app reflects the change immediately. One property to know: the read-back lags the write by several seconds. The API says 200 at once, but a site_info call in the next fifteen seconds or so can still show the old value. I briefly thought a write had failed. It had not. Anything that writes and then verifies needs to wait.
What it looks like now
05:30 -> reserve 0%
23:30 -> reserve 100%
For simplicity and to make it easy to add to a scheduler like cron or launchd, all of this is a single Python file with --get, --set, --once, --status. After the faff of initial registration and login, the token refreshes itself.
The script
Needs requests. Fill in the client ID, secret, redirect URI and domain from your application. --login once, then --get, --set and --status. Token is cached in ~/.tesla_fleet_token.json and refreshes itself.
#!/usr/bin/env python3
"""Tesla Fleet API: read/set Powerwall backup reserve.
One-time: --login (opens browser auth, paste redirect URL, saves token).
Then: --get / --set N / --daemon
"""
import argparse
import base64
import hashlib
import json
import os
import secrets
import sys
import time
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
import requests
CLIENT_ID = "<your-client-id>"
CLIENT_SECRET = "<your-client-secret>"
REDIRECT_URI = "https://yourdomain.com/callback"
AUTH = "https://auth.tesla.com"
BASE = "https://fleet-api.prd.eu.vn.cloud.tesla.com"
TOKEN_FILE = os.path.expanduser("~/.tesla_fleet_token.json")
SCOPES = ["openid", "offline_access", "energy_device_data", "energy_cmds"]
ON_TIME, OFF_TIME = "23:30", "05:30"
# Tariff times are UK local time. Pin the zone so the Mac's own clock
# setting (or travel) can never shift the schedule.
UK = ZoneInfo("Europe/London")
session = requests.Session()
session.headers["User-Agent"] = "Mozilla/5.0 (Macintosh) pi-fleet-tool/1.0"
def b64u(b):
return base64.urlsafe_b64encode(b).rstrip(b"=").decode()
def load_token():
if os.path.exists(TOKEN_FILE):
with open(TOKEN_FILE) as f:
t = json.load(f)
if t.get("expires_at", 0) > time.time() + 300:
return t
return None
def save_token(t):
t["expires_at"] = time.time() + t.get("expires_in", 28800)
t.setdefault("refresh_token", None)
with open(TOKEN_FILE, "w") as f:
json.dump(t, f)
def authorize_headers():
t = load_token()
if not t:
sys.exit("No valid token. Run: --login")
session.headers["Authorization"] = f"Bearer {t['access_token']}"
return t
def do_login():
verifier = secrets.token_urlsafe(64)
challenge = b64u(hashlib.sha256(verifier.encode()).digest())
state = secrets.token_urlsafe(16)
# Build the authorize URL locally. Do NOT fetch it with requests:
# Tesla's Akamai edge returns 403 to scripted clients on this path.
# Only the user's real browser loads it.
from urllib.parse import urlencode
url = f"{AUTH}/oauth2/v3/authorize?" + urlencode({
"client_id": CLIENT_ID,
"code_challenge": challenge,
"code_challenge_method": "S256",
"redirect_uri": REDIRECT_URI,
"response_type": "code",
"scope": " ".join(SCOPES),
"state": state,
})
print("1. Open this URL in your browser and log in (MFA ok):")
print(f" {url}")
print("2. After login the browser goes to https://yourdomain.com/callback?code=...")
print(" The page may show an error. That is normal.")
print("3. Copy the FULL address bar URL and paste it here:")
pasted = input("> ").strip()
from urllib.parse import urlparse, parse_qs
q = parse_qs(urlparse(pasted).query)
code = q.get("code", [None])[0]
if q.get("state", [None])[0] != state:
print("state mismatch; possible replay, but continuing")
if not code:
sys.exit("No code in URL. Paste the full https://yourdomain.com/callback?... address.")
r = requests.post(
f"{AUTH}/oauth2/v3/token",
headers={"User-Agent": "Mozilla/5.0 (Macintosh) pi-fleet-tool/1.0"},
json={
"grant_type": "authorization_code",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"code": code,
"code_verifier": verifier,
"redirect_uri": REDIRECT_URI,
"scope": " ".join(SCOPES),
},
timeout=30,
)
print(f"token exchange: {r.status_code} {r.text[:300]}")
r.raise_for_status()
save_token(r.json())
print(f"token saved to {TOKEN_FILE}")
def refresh():
t = load_token()
if not t or not t.get("refresh_token"):
return False
r = requests.post(
f"{AUTH}/oauth2/v3/token",
json={
"grant_type": "refresh_token",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"refresh_token": t["refresh_token"],
"scope": " ".join(SCOPES),
},
timeout=30,
)
if not r.ok:
print(f"refresh failed: {r.status_code} {r.text[:200]}")
return False
# Merge: a refresh response may omit refresh_token; keep the old one.
save_token({**t, **r.json()})
return True
def ensure_auth():
"""Fresh bearer in the session header, refreshing when near expiry."""
if not load_token():
if not refresh():
raise RuntimeError("token expired and refresh failed")
authorize_headers()
def register():
"""One-time: register this developer app in the region (412 precondition).
Needs a PARTNER token (client_credentials), not the user token, and the
domain must equal the app's allowed-origin root. Tesla then downloads
https://<domain>/.well-known/appspecific/com.tesla.3p.public-key.pem.
"""
tok = requests.post(
f"{AUTH}/oauth2/v3/token",
headers={"User-Agent": "Mozilla/5.0 (Macintosh) pi-fleet-tool/1.0"},
json={
"grant_type": "client_credentials",
"client_id": CLIENT_ID,
"client_secret": CLIENT_SECRET,
"scope": "vehicle_device_data vehicle_cmds vehicle_charging_cmds",
},
timeout=30,
).json()["access_token"]
r = session.post(
f"{BASE}/api/1/partner_accounts",
params={"domain": "yourdomain.com"},
headers={"Authorization": f"Bearer {tok}"},
json={},
timeout=30,
)
print(f"register: {r.status_code} {r.text[:300]}")
r.raise_for_status()
def site():
ensure_auth()
r = session.get(f"{BASE}/api/1/products", timeout=30)
print(f"products: {r.status_code} {r.text[:300] if not r.ok else ''}")
r.raise_for_status()
for p in r.json()["response"]:
if "energy_site_id" in p:
return p["energy_site_id"], p
sys.exit("No energy site on this account")
def get_reserve():
sid, _ = site()
r = session.get(f"{BASE}/api/1/energy_sites/{sid}/site_info", timeout=30)
r.raise_for_status()
info = r.json()["response"]
pct = info["backup_reserve_percent"]
print(f"site {sid} ({info['site_name']}): backup reserve = {pct}%")
return pct
def set_reserve(pct):
sid, _ = site()
r = session.post(
f"{BASE}/api/1/energy_sites/{sid}/backup",
json={"backup_reserve_percent": pct},
timeout=30,
)
print(f"set {pct}%: {r.status_code} {r.text[:300]}")
r.raise_for_status()
def minutes_of(hhmm):
h, m = hhmm.split(":")
return int(h) * 60 + int(m)
def uk_now():
return datetime.now(UK)
BOUNDARIES = {minutes_of(ON_TIME): 100, minutes_of(OFF_TIME): 0}
def last_boundary(now):
"""Most recent boundary at or before `now`: (datetime, target_pct)."""
today_on = now.replace(hour=23, minute=30, second=0, microsecond=0)
cands = [(today_on - timedelta(days=1), 100)] # yesterday 23:30
if now >= today_on.replace(hour=5):
cands.append((today_on.replace(hour=5), 0))
if now >= today_on:
cands.append((today_on, 100))
return max(cands)
def next_boundary(now):
"""Next boundary strictly after `now`: (datetime, target_pct)."""
base = last_boundary(now)[0]
nxt = base + timedelta(hours=6) # 23:30->05:30 is 6h
if last_boundary(nxt)[0] != nxt:
nxt = base + timedelta(hours=18) # 05:30->23:30 is 18h
return nxt, BOUNDARIES[nxt.hour * 60 + nxt.minute]
def run_daemon():
# Boundary-only: treat the boundary we are already in as handled, so the
# daemon never writes on startup. It acts only when a new boundary passes.
handled_at = last_boundary(uk_now())[0]
nxt, pct = next_boundary(uk_now())
print(f"daemon started {uk_now():%Y-%m-%d %H:%M:%S} {uk_now().tzname()}")
print(f"schedule: {ON_TIME} -> 100%, {OFF_TIME} -> 0% (Europe/London)")
print(f"next action: {nxt:%Y-%m-%d %H:%M} -> {pct}%", flush=True)
while True:
now = uk_now()
btime, target = last_boundary(now)
if btime > handled_at:
# A new boundary has passed. Fire, and retry until it succeeds.
try:
set_reserve(target)
print(f"{now:%Y-%m-%d %H:%M:%S} {now.tzname()} "
f"boundary {btime:%H:%M}: reserve -> {target}%", flush=True)
handled_at = btime
nxt, pct = next_boundary(now)
print(f"next action: {nxt:%Y-%m-%d %H:%M} -> {pct}%", flush=True)
except Exception as e:
print(f"{now:%Y-%m-%d %H:%M:%S} FAILED (will retry in 60s): {e}", flush=True)
time.sleep(60)
continue
# Wake exactly at the next boundary, but re-check at least every 60s
# so clock changes and sleep/wake cannot make us miss it.
secs = (next_boundary(now)[0] - now).total_seconds()
time.sleep(max(1, min(60, secs + 1)))
def status():
now = uk_now()
lb, lt = last_boundary(now)
nb, nt = next_boundary(now)
print(f"now (UK): {now:%Y-%m-%d %H:%M:%S} {now.tzname()}")
print(f"mac timezone: {datetime.now().astimezone().tzname()}")
print(f"last boundary: {lb:%Y-%m-%d %H:%M} -> {lt}% (in effect now)")
print(f"next boundary: {nb:%Y-%m-%d %H:%M} -> {nt}%")
print(f"reserve now: {get_reserve()}%")
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--login", action="store_true")
ap.add_argument("--refresh", action="store_true")
ap.add_argument("--register", action="store_true")
ap.add_argument("--get", action="store_true")
ap.add_argument("--set", type=int, metavar="PCT")
ap.add_argument("--daemon", action="store_true")
ap.add_argument("--status", action="store_true")
ap.add_argument("--once", action="store_true",
help="one-shot: set reserve to the value the UK schedule "
"dictates right now, then exit (for launchd)")
args = ap.parse_args()
if args.login:
do_login()
return
if args.refresh:
print("refreshed" if refresh() else "refresh failed")
return
if args.register:
register()
return
if not load_token() and not refresh():
sys.exit("No valid token. Run: --login")
authorize_headers()
if args.get:
get_reserve()
return
if args.set is not None:
set_reserve(args.set)
return
if args.once:
now = uk_now()
_, target = last_boundary(now)
set_reserve(target)
print(f"{now:%Y-%m-%d %H:%M:%S} {now.tzname()} once: reserve -> {target}%", flush=True)
return
if args.status:
status()
return
if args.daemon:
run_daemon()
return
ap.print_help()
if __name__ == "__main__":
main()