public TeslaConnector() { if (_client == null) { _client = new HttpClient(); } _credentials = TeslaCredentials.LoadFromFile(API_FILE); }
/// <summary> /// Loads the credentials from the provided file and returns a new EcobeeCredentials /// </summary> /// <param name="file">File to load from</param> /// <returns>Credentials object</returns> public static TeslaCredentials LoadFromFile(string file) { if (File.Exists(file)) { string contents = File.ReadAllText(file); TeslaCredentials creds = JsonConvert.DeserializeObject <TeslaCredentials>(contents); return(creds); } return(new TeslaCredentials()); }
public async Task <bool> RefreshTokenAsync() { if (!_credentials.CheckValidity()) { throw new UnauthorizedAccessException(UNCONFIGURED_EXCEPTION); } //use the refresh token to refresh the access token Dictionary <string, string> anonContent = new Dictionary <string, string> { ["grant_type"] = "refresh_token", ["refresh_token"] = _credentials.RefreshToken, ["client_id"] = CLIENT_ID, ["client_secret"] = CLIENT_SECRET }; try { HttpRequestMessage request = createRequest(HttpMethod.Post, AUTH_URL, anonContent, false); HttpResponseMessage response = await _client.SendAsync(request); if (response.IsSuccessStatusCode) { string content = await response.Content.ReadAsStringAsync(); _credentials = JsonConvert.DeserializeObject <TeslaCredentials>(content); _credentials.WriteToFile(API_FILE); return(true); } } catch (Exception) { throw; } return(false); }