-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPulseService.cs
85 lines (77 loc) · 3.36 KB
/
PulseService.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using Newtonsoft.Json;
using RestSharp;
using RestSharp.Serializers.NewtonsoftJson;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TeslaChargingManager.Pulse;
namespace TeslaChargingManager
{
internal static class PulseService
{
private static DateTime accessTokenExpiresOn = DateTime.MinValue;
private static string accessToken;
private static AppSettings appSettings;
private static RestClient client;
internal static int SiteId { get; set; }
internal static void Init(AppSettings _appSettings)
{
appSettings = _appSettings;
if (client == null) client = new RestClient(appSettings.PulseUrl);
RefreshAccessToken();
}
private static void RefreshAccessToken()
{
if (DateTime.UtcNow > accessTokenExpiresOn)
{
var refreshClient = new RestClient("https://cognito-idp.ap-southeast-2.amazonaws.com");
refreshClient.AddDefaultHeader("X-Amz-Target", "AWSCognitoIdentityProviderService.InitiateAuth");
refreshClient.AddDefaultHeader("Content-Type", "application/x-amz-json-1.1");
var refreshRequest = new RestRequest(Method.POST);
refreshRequest.AddJsonBody(new RefreshTokenRequest
{
ClientId = appSettings.PulseClientId,
AuthParameters = new AuthParameters { REFRESH_TOKEN = appSettings.PulseRefreshToken }
});
var refreshResponse = refreshClient.Execute(refreshRequest);
if (refreshResponse.IsSuccessful)
{
var data = JsonConvert.DeserializeObject<RefreshTokenResponse>(refreshResponse.Content);
accessTokenExpiresOn = DateTime.UtcNow.AddSeconds(data.AuthenticationResult.ExpiresIn);
accessToken = data.AuthenticationResult.IdToken;
client.AddOrUpdateDefaultParameter(new Parameter("Authorization", $"Bearer {accessToken}", ParameterType.HttpHeader));
}
}
}
internal static UserModel GetUser()
{
RefreshAccessToken();
var pulseRequest = new RestRequest($"v1/user");
var pulseResponse = client.Get<UserModel>(pulseRequest);
return pulseResponse.Data;
}
internal static SiteListModel GetSites()
{
RefreshAccessToken();
var pulseRequest = new RestRequest($"v1/sites");
var pulseResponse = client.Get<SiteListModel>(pulseRequest);
return pulseResponse.Data;
}
internal static SiteModel GetSite()
{
RefreshAccessToken();
var pulseRequest = new RestRequest($"v1/sites/{SiteId}");
var pulseResponse = client.Get<SiteModel>(pulseRequest);
return pulseResponse.Data;
}
internal static SummaryModel GetLiveSummary()
{
RefreshAccessToken();
var pulseRequest = new RestRequest($"v1/sites/{SiteId}/live_data_summary");
var pulseResponse = client.Get<SummaryModel>(pulseRequest);
return pulseResponse.Data;
}
}
}