/// <summary> /// Get an access token for the Netatmo API. /// </summary> /// <param name="log">TraceWriter to log to</param> /// <returns>string</returns> private static async Task <string> GetAccessToken(TraceWriter log) { string accessToken = string.Empty; // If we have a non-expired access token if (HaveValidAccessToken(log)) { accessToken = Environment.GetEnvironmentVariable(EnvNetatmoAccessToken); } else { NetatmoAccessToken tokenObject = null; // Check if we have already received an initial token and need to only refresh var needRefresh = Environment.GetEnvironmentVariable(EnvNetatmoAccessTokenRefreshAsNeeded); if (string.IsNullOrEmpty(needRefresh) || !needRefresh.Equals("true")) { log.Info($"Getting a new access token..."); tokenObject = await GetNewAccessToken(log); } else { log.Info($"Refreshing the access token..."); tokenObject = await RefreshAccessToken(log); } if (tokenObject != null) { var now = DateTime.UtcNow; var expiresAt = DateTime.UtcNow.AddSeconds(tokenObject.ExpiresIn); Environment.SetEnvironmentVariable(EnvNetatmoAccessTokenRefreshAsNeeded, "true"); Environment.SetEnvironmentVariable(EnvNetatmoAccessToken, tokenObject.AccessToken); Environment.SetEnvironmentVariable(EnvNetatmoAccessTokenExpiresAt, expiresAt.ToString()); Environment.SetEnvironmentVariable(EnvNetatmoRefreshToken, tokenObject.RefreshToken); } accessToken = tokenObject?.AccessToken; } return(accessToken); }
/// <summary> /// Refresh the access token for the Netatmo API /// </summary> /// <param name="log">TraceWriter to log to</param> /// <returns>NetatmoAccessToken</returns> private static async Task <NetatmoAccessToken> RefreshAccessToken(TraceWriter log) { NetatmoAccessToken accessToken = null; using (var http = new HttpClient()) { var clientId = Environment.GetEnvironmentVariable(EnvNetatmoClientId); var parameters = new Dictionary <string, string> { { "client_id", clientId }, { "client_secret", Environment.GetEnvironmentVariable(EnvNetatmoClientSecret) }, { "username", Environment.GetEnvironmentVariable(EnvNetatmoEmail) }, { "password", Environment.GetEnvironmentVariable(EnvNetatmoPassword) }, { "grant_type", "refresh_token" }, { "scope", "read_station" }, { "token_type", "bearer" }, { "access_token", Environment.GetEnvironmentVariable(EnvNetatmoAccessToken) }, { "refresh_token", Environment.GetEnvironmentVariable(EnvNetatmoRefreshToken) }, }; var request = new HttpRequestMessage(HttpMethod.Post, NetatmoUriAccessToken) { Content = new FormUrlEncodedContent(parameters) }; var response = await http.SendAsync(request); if (response.IsSuccessStatusCode) { var json = await response.Content.ReadAsStringAsync(); accessToken = NetatmoAccessToken.FromJson(json); } else { log.Error($"ERROR getting the access token: HTTP Status {response.StatusCode} - {response.ReasonPhrase}"); } } return(accessToken); }