Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for vehicle command proxy / FleetAPI #546

Merged
merged 8 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions etc/twcmanager/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,36 @@
# you will need to un-comment it to have it take effect.
#"minChargeLevel": 10,

# The Tesla API URL is base URL for all REST API calls. This should
# include the "/api/1/vehicles" path.
# Known values are:
#
# OwnerAPI (legacy): https://owner-api.teslamotors.com/api/1/vehicles
# FleetAPI North America: https://fleet-api.prd.na.vn.cloud.tesla.com/api/1/vehicles
# FleetAPI Europe: https://fleet-api.prd.eu.vn.cloud.tesla.com/api/1/vehicles
# FleetAPI China: https://fleet-api.prd.cn.vn.cloud.tesla.cn/api/1/vehicles
# FleetAPI http proxy: https://localhost:4443/api/1/vehicles
"teslaApiUrl": "https://fleet-api.prd.na.vn.cloud.tesla.com/api/1/vehicles",

# The client_id of the app registered with Tesla. Registration is
# required to use the FleetAPI and Vehicle Command protocol.
# See https://developer.tesla.com/docs/fleet-api#authentication
#"teslaApiClientID": "client-id-of-registered-app",

# Since 2024 the Tesla Vehicle Command protocol is required for all
# vehicles manufacturered after 2021. The Tesla Vehicle Command proxy
# will automatically fall back to the FleetAPI for older vehicles.
#
# TWCManager does not implement the Tesla Vehicle Command protocol.
# Instead it relies on the Tesla Vehicle Command proxy which translates
# the FleetAPI REST calls if the destination vehicle supports the
# new protocol. This requires the URL of the proxy to be set as
# "teslaApiUrl" above and the proxy certificate for validation here.
# See https://github.com/teslamotors/vehicle-command
#
# Only set "httpProxyCert" when setting "teslaApiUrl" to a local proxy.
#"httpProxyCert": "/path/to/public_key.pem",

# The cloudUpdateInterval determines how often to poll certain
# data retrieved from the Tesla API to evaluate policy.
"cloudUpdateInterval": 1800,
Expand Down
49 changes: 29 additions & 20 deletions lib/TWCManager/Vehicle/TeslaAPI.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ class TeslaAPI:
__apiState = None
__authURL = "https://auth.tesla.com/oauth2/v3/token"
__callbackURL = "https://auth.tesla.com/void/callback"
baseURL = "https://owner-api.teslamotors.com/api/1/vehicles"
refreshClientID = "ownerapi"
proxyCert = None
carApiLastErrorTime = 0
carApiBearerToken = ""
carApiRefreshToken = ""
Expand Down Expand Up @@ -61,6 +64,9 @@ def __init__(self, master):
self.master = master
try:
self.config = master.config
self.baseURL = self.config["config"].get("teslaApiUrl", "https://owner-api.teslamotors.com/api/1/vehicles")
self.refreshClientID = self.config["config"].get("teslaApiClientID", "ownerapi")
self.proxyCert = self.config["config"].get("httpProxyCert", True)
self.minChargeLevel = self.config["config"].get("minChargeLevel", -1)
self.chargeUpdateInterval = self.config["config"].get(
"cloudUpdateInterval", 1800
Expand Down Expand Up @@ -104,10 +110,9 @@ def apiRefresh(self):
# days when first issued, so we'll get a new token every 15 days.
headers = {"accept": "application/json", "Content-Type": "application/json"}
data = {
"client_id": "ownerapi",
"client_id": self.refreshClientID,
"grant_type": "refresh_token",
"refresh_token": self.getCarApiRefreshToken(),
"scope": "openid email offline_access",
}
req = None
now = time.time()
Expand Down Expand Up @@ -219,13 +224,13 @@ def car_api_available(

if self.getCarApiBearerToken() != "":
if self.getVehicleCount() < 1:
url = "https://owner-api.teslamotors.com/api/1/vehicles"
url = self.baseURL
headers = {
"accept": "application/json",
"Authorization": "Bearer " + self.getCarApiBearerToken(),
}
try:
req = requests.get(url, headers=headers)
req = requests.get(url, headers=headers, verify=self.proxyCert)
logger.log(logging.INFO8, "Car API cmd vehicles " + str(req))
apiResponseDict = json.loads(req.text)
except requests.exceptions.RequestException:
Expand Down Expand Up @@ -639,8 +644,8 @@ def car_api_charge(self, charge):
if charge:
self.applyChargeLimit(self.lastChargeLimitApplied, checkArrival=True)

url = "https://owner-api.teslamotors.com/api/1/vehicles/"
url = url + str(vehicle.ID) + "/command/charge_" + startOrStop
url = self.baseURL + "/"
url = url + str(vehicle.VIN) + "/command/charge_" + startOrStop
headers = {
"accept": "application/json",
"Authorization": "Bearer " + self.getCarApiBearerToken(),
Expand All @@ -649,7 +654,7 @@ def car_api_charge(self, charge):
# Retry up to 3 times on certain errors.
for _ in range(0, 3):
try:
req = requests.post(url, headers=headers)
req = requests.post(url, headers=headers, verify=self.proxyCert)
logger.log(
logging.INFO8,
"Car API cmd charge_" + startOrStop + " " + str(req),
Expand Down Expand Up @@ -1113,8 +1118,8 @@ def setChargeRate(self, charge_rate, vehicle=None, set_again=False):

vehicle.lastAPIAccessTime = time.time()

url = "https://owner-api.teslamotors.com/api/1/vehicles/"
url = url + str(vehicle.ID) + "/command/set_charging_amps"
url = self.baseURL + "/"
url = url + str(vehicle.VIN) + "/command/set_charging_amps"

headers = {
"accept": "application/json",
Expand All @@ -1124,7 +1129,7 @@ def setChargeRate(self, charge_rate, vehicle=None, set_again=False):
body = {"charging_amps": charge_rate}

try:
req = requests.post(url, headers=headers, json=body)
req = requests.post(url, headers=headers, json=body, verify=self.proxyCert)
logger.log(
logging.INFO8,
f"Car API cmd set_charging_amps {charge_rate}A {str(req)}",
Expand Down Expand Up @@ -1174,15 +1179,15 @@ def wakeVehicle(self, vehicle):
apiResponseDict = None
vehicle.lastAPIAccessTime = time.time()

url = "https://owner-api.teslamotors.com/api/1/vehicles/"
url = url + str(vehicle.ID) + "/wake_up"
url = self.baseURL + "/"
url = url + str(vehicle.VIN) + "/wake_up"

headers = {
"accept": "application/json",
"Authorization": "Bearer " + self.getCarApiBearerToken(),
}
try:
req = requests.post(url, headers=headers)
req = requests.post(url, headers=headers, verify=self.proxyCert)
logger.log(logging.INFO8, "Car API cmd wake_up" + str(req))
apiResponseDict = json.loads(req.text)
except requests.exceptions.RequestException:
Expand Down Expand Up @@ -1210,6 +1215,8 @@ class CarApiVehicle:
carapi = None
__config = None
debuglevel = 0
baseURL = "https://owner-api.teslamotors.com/api/1/vehicles"
proxyCert = None
ID = None
name = ""
syncSource = "TeslaAPI"
Expand Down Expand Up @@ -1243,6 +1250,8 @@ class CarApiVehicle:
def __init__(self, json, carapi, config):
self.carapi = carapi
self.__config = config
self.baseURL = config["config"].get("teslaApiUrl", "https://owner-api.teslamotors.com/api/1/vehicles")
self.proxyCert = config["config"].get("httpProxyCert", None)
self.ID = json["id"]
self.VIN = json["vin"]
self.name = json["display_name"]
Expand Down Expand Up @@ -1312,7 +1321,7 @@ def ready(self):
# Permits opportunistic API requests
def is_awake(self):
if self.syncSource == "TeslaAPI":
url = "https://owner-api.teslamotors.com/api/1/vehicles/" + str(self.ID)
url = self.baseURL + "/" + str(self.VIN)
(result, response) = self.get_car_api(
url, checkReady=False, provesOnline=False
)
Expand All @@ -1339,7 +1348,7 @@ def get_car_api(self, url, checkReady=True, provesOnline=True):
# Retry up to 3 times on certain errors.
for _ in range(0, 3):
try:
req = requests.get(url, headers=headers)
req = requests.get(url, headers=headers, verify=self.proxyCert)
logger.log(logging.INFO8, "Car API cmd " + url + " " + str(req))
apiResponseDict = json.loads(req.text)
# This error can happen here as well:
Expand Down Expand Up @@ -1398,8 +1407,8 @@ def update_location(self, cacheTime=60):
return True

def update_vehicle_data(self, cacheTime=60):
url = "https://owner-api.teslamotors.com/api/1/vehicles/"
url = url + str(self.ID) + "/vehicle_data"
url = self.baseURL + "/"
url = url + str(self.VIN) + "/vehicle_data"
url = (
url
+ "?endpoints=location_data%3Bcharge_state%3Bclimate_state%3Bvehicle_state%3Bgui_settings%3Bvehicle_config"
Expand Down Expand Up @@ -1455,8 +1464,8 @@ def apply_charge_limit(self, limit):

self.lastLimitAttemptTime = now

url = "https://owner-api.teslamotors.com/api/1/vehicles/"
url = url + str(self.ID) + "/command/set_charge_limit"
url = self.baseURL + "/"
url = url + str(self.VIN) + "/command/set_charge_limit"

headers = {
"accept": "application/json",
Expand All @@ -1466,7 +1475,7 @@ def apply_charge_limit(self, limit):

for _ in range(0, 3):
try:
req = requests.post(url, headers=headers, json=body)
req = requests.post(url, headers=headers, json=body, verify=self.proxyCert)
logger.log(logging.INFO8, "Car API cmd set_charge_limit " + str(req))

apiResponseDict = json.loads(req.text)
Expand Down