13.12.2018, 22:50
(This post was last modified: 13.12.2018, 23:11 by Erwin van der Zwart.)
Hi,
Usually the bearer token is a response on the token request and is valid for x minutes (mostly 60 minutes), so i doubt that 123 is the bearer code (:
Can you try this?
BR,
Erwin
Usually the bearer token is a response on the token request and is valid for x minutes (mostly 60 minutes), so i doubt that 123 is the bearer code (:
Can you try this?
Code:
-- Load modules
require('json')
require('ssl.https')
require('ltn12')
-- Set credentials for Tesla API
username = "admin"
password = "admin"
function GetToken()
request_token_url = 'https://owner-api.teslamotors.com/oauth/token'
local response_body = {}
local request_body = "grant_type=password&username=" .. username .. "&password=" .. password
local body, code, hdrs, stat = ssl.https.request{
url = request_token_url;
method = "POST";
headers =
{
["Content-Type"] = "application/x-www-form-urlencoded";
["Content-Length"] = #request_body;
};
source = ltn12.source.string(request_body);
sink = ltn12.sink.table(response_body);
}
if code == 200 then
ret = table.concat(response_body)
ret = json.pdecode(ret)
return ret.access_token -- could be some other field, try to log ret to be sure
end
end
-- Request token
if not API_Token then
API_Token = GetToken()
end
function RequestFromTesla(request)
request_url = 'https://owner-api.teslamotors.com/api/1/' .. request
local response_body = {}
local request_body = ""
local body, code, hdrs, stat = ssl.https.request{
url = request_url;
method = "GET";
headers =
{
["Content-Type"] = "application/json";
["Authorization"] = "Bearer " .. API_Token;
};
source = ltn12.source.string(request_body);
sink = ltn12.sink.table(response_body);
}
if code == 200 then
ret = table.concat(response_body)
ret = json.pdecode(ret)
return ret
else
API_Token = GetToken() -- request a new token
end
end
function WriteToTesla(request)
request_url = 'https://owner-api.teslamotors.com/api/1/' .. request
local response_body = {}
local request_body = ""
local body, code, hdrs, stat = ssl.https.request{
url = request_url;
method = "POST";
headers =
{
["Content-Type"] = "application/json";
["Authorization"] = "Bearer " .. API_Token;
};
source = ltn12.source.string(request_body);
sink = ltn12.sink.table(response_body);
}
if code == 200 then
ret = table.concat(response_body)
ret = json.pdecode(ret)
return ret
else
API_Token = GetToken() -- request a new token
end
end
-- Get products
products = RequestFromTesla('products')
log(products) -- Check here your Car ID
CarID = 1 -- products[1].id?
-- Get onboarding data
onboarding_data = RequestFromTesla('users/onboarding_data')
log(onboarding_data)
-- Wake up car
result = WriteToTesla('vehicles/' .. CarID .. '/wake_up')
log(result)
Erwin