-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfunctions.py
129 lines (118 loc) · 4.42 KB
/
functions.py
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import requests
import dotenv
import os
import csv
dotenv.load_dotenv('./.env', override=True)
SITEKEY = os.getenv('site_key')
TOKEN = os.getenv('token')
URL = "https://edp-api-graphql.edp.sunpower.com/graphql"
USERNAME = os.getenv("username")
PASSWORD = os.getenv("password")
def get_token():
"""
TODO: Get jwt using session token.
This function currently gets the login response from basic username/password login.
I am as yet unsure how SunPower's OAuth2 flow results in a JSON Web Token (jwt) from this.
"""
auth_url = "https://login.mysunpower.com/api/v1/authn"
headers = {"Accept": "application/json", "Content-Type": "application/json"}
payload = {"password": PASSWORD, "username": USERNAME}
return requests.post(auth_url,headers=headers, json=payload).json()
HEADERS = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-US,en;q=0.9",
"Connection": "keep-alive",
"Content-Type": "application/json",
"Host": "edp-api-graphql.edp.sunpower.com",
"Origin": "https://sds.mysunpower.com",
"Referer": "https://sds.mysunpower.com/",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "cross-site",
"Authorization": f"Bearer {TOKEN}" # TODO: Replace TOKEN with get_token() once the function returns a jwt
}
def get_aggregates(start, end):
query = {
"operationName": "EnergyRange",
"variables": {
"siteKey": SITEKEY,
"interval": "hour",
"end": end,
"start": start
},
"query": """
query EnergyRange($interval: String!, $end: String!, $start: String!, $siteKey: String!) {
energyRange(interval: $interval, end: $end, start: $start, siteKey: $siteKey) {
totalProduction
totalConsumption
energyMixPercentage
totalGridImport
totalGridExport
netGridImportExport
}
}
"""
}
response = requests.post(URL, headers=HEADERS, json=query).json()
try:
totals = {key: response["data"]["energyRange"][key] for key in ["totalProduction","totalConsumption","energyMixPercentage","totalGridImport","totalGridExport","netGridImportExport"]}
return totals
except Exception:
print(response)
def get_timeseries(start, end):
query = {
"operationName": "EnergyRange",
"variables": {
"siteKey": SITEKEY,
"interval": "hour",
"end": end,
"start": start
},
"query": """
query EnergyRange($interval: String!, $end: String!, $start: String!, $siteKey: String!) {
energyRange(interval: $interval, end: $end, start: $start, siteKey: $siteKey) {
energyDataSeries {
consumption
grid
production
}
}
}
"""
}
response = requests.post(URL, headers=HEADERS, json=query).json()
if not response["data"]:
print(response)
print("You probably need a new token.")
raise ValueError
# combine timeseries for production, consumption, and grid
# get timestamps and populate consumption.
timeseries = {reading[0]: {"consumption": reading[1]} for reading in response["data"]["energyRange"]["energyDataSeries"]["consumption"]}
# add production
for reading in response["data"]["energyRange"]["energyDataSeries"]["production"]:
timeseries[reading[0]]["production"] = reading[1]
# add grid
for reading in response["data"]["energyRange"]["energyDataSeries"]["grid"]:
timeseries[reading[0]]["grid"] = reading[1]
# flatten
final_timeseries = []
for timestamp in timeseries:
final_timeseries.append(
{
"ts": timestamp.replace('T',' '),
"consumption": timeseries[timestamp]["consumption"],
"production": timeseries[timestamp]["production"],
"grid": timeseries[timestamp]["grid"]
}
)
return final_timeseries
def write_timeseries(path, timeseries):
with open(path, mode='a', newline='') as file:
writer = csv.DictWriter(file, fieldnames=['ts', 'consumption', 'production', 'grid'])
if os.path.getsize(path) == 0:
writer.writeheader()
for row in timeseries:
writer.writerow(row)
if __name__ == "__main__":
print(get_aggregates("2024-03-10T00:00:00", "2024-03-10T23:59:59"))