Skip to content

Commit

Permalink
Bugfixes
Browse files Browse the repository at this point in the history
  • Loading branch information
bassmaster187 committed Jan 30, 2024
1 parent a09f2af commit 9c94de9
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 37 deletions.
20 changes: 20 additions & 0 deletions TeslaLogger/Car.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,9 @@ public Car(int CarInDB, string TeslaName, string TeslaPasswort, int CarInAccount
};
thread.Start();

if (VIN2DBCarID.ContainsKey(vin))
VIN2DBCarID.Remove(vin);

VIN2DBCarID.Add(vin, CarInDB);
}
}
Expand Down Expand Up @@ -472,6 +475,9 @@ internal void ExitCarThread(string v)
run = false;
thread.Abort();
Allcars.Remove(this);

if (VIN2DBCarID.ContainsKey(vin))
VIN2DBCarID.Remove(vin);
}

public void ThreadJoin()
Expand Down Expand Up @@ -1841,5 +1847,19 @@ internal EventBuilder CreateExeptionlessFeature(string feature)

return b;
}

public bool UseCommandProxyServer()
{
if (FleetAPI)
{
if (CarType == "models" || CarType == "modelx" || CarType == "models2")
return false;

return true;
}


return false;
}
}
}
110 changes: 75 additions & 35 deletions TeslaLogger/WebHelper.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using Exceptionless;
using Google.Protobuf.WellKnownTypes;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI;
using Newtonsoft.Json;
Expand Down Expand Up @@ -235,7 +236,7 @@ public bool RestoreToken()

TimeSpan ts = DateTime.Now - car.Tesla_Token_Expire;

if (ts.TotalDays < 30)
if (ts.TotalDays < 8)
{
Tesla_token = car.Tesla_Token;
lastTokenRefresh = car.Tesla_Token_Expire;
Expand Down Expand Up @@ -582,39 +583,12 @@ internal string UpdateTeslaTokenFromRefreshToken()

string access_token = jsonResult["access_token"] ?? throw new Exception("access_token Missing");
string new_refresh_token = jsonResult["refresh_token"] ?? throw new Exception("refresh_token Missing");

if (new_refresh_token == null || new_refresh_token.Length < 10)
{
Log("new Refresh Token is invalid!!");
}
else if ( new_refresh_token == refresh_token)
{
Log("refresh_token not changed");
}
else
{
car.DbHelper.UpdateRefreshToken(new_refresh_token);
}
CheckNewRefreshToken(refresh_token, new_refresh_token);

// as of March 21 2022 Tesla returns a bearer token. GetTokenAsync4 is no longer neeaded.
car.CreateExeptionlessLog("Tesla Token", "UpdateTeslaTokenFromRefreshToken Success", Exceptionless.Logging.LogLevel.Info).Submit();
Tesla_token = jsonResult["access_token"];
car.Tesla_Token = Tesla_token;
car.DbHelper.UpdateTeslaToken();
car.LoginRetryCounter = 0;

try
{
var c = GethttpclientTeslaAPI(true); // dispose old client and create a new Client with new token.
_ = IsOnline(true).Result; // get new Tesla_Streamingtoken;
// restart streaming thread with new token
RestartStreamThreadWithTask();
}
catch (Exception ex)
{
car.CreateExceptionlessClient(ex).AddObject(HttpStatusCode, "HTTP StatusCode").AddObject(resultContent, "ResultContent").Submit();
car.Log("Refresh TeslaToken and Streamingtoken: " + ex.ToString());
}
string Token = jsonResult["access_token"];
SetNewAccessToken(Token);

return Tesla_token;

Expand All @@ -639,6 +613,43 @@ internal string UpdateTeslaTokenFromRefreshToken()
return "";
}

private void CheckNewRefreshToken(string refresh_token, string new_refresh_token)
{
if (new_refresh_token == null || new_refresh_token.Length < 10)
{
Log("new Refresh Token is invalid!!");
}
else if (new_refresh_token == refresh_token)
{
Log("refresh_token not changed");
}
else
{
car.DbHelper.UpdateRefreshToken(new_refresh_token);
}
}

void SetNewAccessToken(string access_token)
{
Tesla_token = access_token;
car.Tesla_Token = access_token;
car.Tesla_Token_Expire = DateTime.Now;
car.LoginRetryCounter = 0;
car.DbHelper.UpdateTeslaToken();

try
{
var c = GethttpclientTeslaAPI(true); // dispose old client and create a new Client with new token.
_ = IsOnline(true).Result; // get new Tesla_Streamingtoken;
// restart streaming thread with new token
RestartStreamThreadWithTask();
}
catch (Exception ex)
{
car.Log("SetNewAccessToken: " + ex.ToString());
}
}

private string UpdateTeslaTokenFromRefreshTokenFromFleetAPI(string refresh_token)
{
try
Expand All @@ -665,8 +676,19 @@ private string UpdateTeslaTokenFromRefreshTokenFromFleetAPI(string refresh_token
string result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
if (result.Contains("\"error\""))
{
car.Log(result);
return "";
}

dynamic j = JsonConvert.DeserializeObject(result);
string access_token = j["access_token"];

string new_refresh_token = j["refresh_token"];
CheckNewRefreshToken(refresh_token, new_refresh_token);

SetNewAccessToken(access_token);
return access_token;
}
else
Expand Down Expand Up @@ -1409,9 +1431,8 @@ private string GetTokenAsync4(string access_token)
int created_at = jsonResult["created_at"] ?? throw new Exception("created_at Missing");
int expires_in = jsonResult["expires_in"] ?? throw new Exception("expires_in Missing");

Tesla_token = jsonResult["access_token"];
car.DbHelper.UpdateTeslaToken();
car.LoginRetryCounter = 0;
String token = jsonResult["access_token"];
SetNewAccessToken(token);
return Tesla_token;
}
}
Expand Down Expand Up @@ -1672,6 +1693,9 @@ HttpClient GethttpclientTeslaAPI(bool forceNewClient = false)

if (httpclientTeslaAPI == null)
{
if (String.IsNullOrEmpty(Tesla_token) || Tesla_token == "NULL")
car.Log("ERROR: Create HTTP Client with wrong Tesla Token!");

httpclientTeslaAPI = new HttpClient();
{
httpclientTeslaAPI.DefaultRequestHeaders.Add("x-tesla-user-agent", "TeslaApp/3.4.4-350/fad4a582e/android/8.1.0");
Expand Down Expand Up @@ -4729,6 +4753,8 @@ public async Task<string> GetChargingHistoryV2(int pageNumber = 1)

public async Task<string> PostCommand(string cmd, string data, bool _json = false)
{
bool proxyServer = car.UseCommandProxyServer();

Log("PostCommand: " + cmd + " - " + data);
string cacheKey = "PostCommand" + car.CarInDB;
object cacheValue = MemoryCache.Default.Get(cacheKey);
Expand All @@ -4745,7 +4771,19 @@ public async Task<string> PostCommand(string cmd, string data, bool _json = fals
{
HttpClient client = GethttpclientTeslaAPI();

string url = apiaddress + "api/1/vehicles/" + Tesla_id + "/" + cmd;
string url = apiaddress+ "api/1/vehicles/" + Tesla_id + "/" + cmd;

if (proxyServer)
{
car.Log("Use ProxyServer");
url = "https://teslalogger.de:4444/api/1/vehicles/" + car.Vin + "/" + cmd;
}
else if (car.FleetAPI) // Old model s / x
{
car.Log("Old Model S/X currenty not supported");
url = "https://owner-api.teslamotors.com/api/1/vehicles/" + Tesla_id + "/" + cmd;

}

StringContent queryString = null;
try
Expand Down Expand Up @@ -4777,6 +4815,8 @@ public async Task<string> PostCommand(string cmd, string data, bool _json = fals
}
}

car.Log("Response: " + resultContent);

return resultContent;
}
finally
Expand Down
6 changes: 4 additions & 2 deletions TeslaLogger/WebServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2404,7 +2404,7 @@ UNION ALL

Logfile.Log($"New CarID: {newid} SQL Query result: <{queryresult}>");

using (var cmd2 = new MySqlCommand("insert cars (id, tesla_name, tesla_password, vin, display_name, freesuc, tesla_token, refresh_token) values (@id, @tesla_name, @tesla_password, @vin, @display_name, @freesuc, @tesla_token, @refresh_token)", con))
using (var cmd2 = new MySqlCommand("insert cars (id, tesla_name, tesla_password, vin, display_name, freesuc, tesla_token, refresh_token, tesla_token_expire) values (@id, @tesla_name, @tesla_password, @vin, @display_name, @freesuc, @tesla_token, @refresh_token, @tesla_token_expire)", con))
{
cmd2.Parameters.AddWithValue("@id", newid);
cmd2.Parameters.AddWithValue("@tesla_name", email);
Expand All @@ -2414,6 +2414,7 @@ UNION ALL
cmd2.Parameters.AddWithValue("@freesuc", freesuc ? 1 : 0);
cmd2.Parameters.AddWithValue("@tesla_token", access_token);
cmd2.Parameters.AddWithValue("@refresh_token", refresh_token);
cmd.Parameters.AddWithValue("@tesla_token_expire", DateTime.Now);
_ = SQLTracer.TraceNQ(cmd2, out _);

#pragma warning disable CA2000 // Objekte verwerfen, bevor Bereich verloren geht
Expand All @@ -2434,13 +2435,14 @@ UNION ALL
{
con.Open();

using (MySqlCommand cmd = new MySqlCommand("update cars set freesuc=@freesuc, tesla_token=@tesla_token, refresh_token=@refresh_token, fleetAPI=@fleetAPI where id=@id", con))
using (MySqlCommand cmd = new MySqlCommand("update cars set freesuc=@freesuc, tesla_token=@tesla_token, refresh_token=@refresh_token, fleetAPI=@fleetAPI, tesla_token_expire=@tesla_token_expire where id=@id", con))
{
cmd.Parameters.AddWithValue("@id", dbID);
cmd.Parameters.AddWithValue("@freesuc", freesuc ? 1 : 0);
cmd.Parameters.AddWithValue("@tesla_token", access_token);
cmd.Parameters.AddWithValue("@refresh_token", refresh_token);
cmd.Parameters.AddWithValue("@fleetAPI", FleetAPI ? 1 : 0);
cmd.Parameters.AddWithValue("@tesla_token_expire", DateTime.Now);
_ = SQLTracer.TraceNQ(cmd, out _);

Car c = Car.GetCarByID(dbID);
Expand Down

0 comments on commit 9c94de9

Please sign in to comment.